Thursday, 15 October 2015

How to move list item attachment from one list to another list in SharePoint office 365 using REST API

Getting attachment from one list and post it in another list
var hostweburl;
var appweburl;
var FileName;
var serverrelativeurl;
// This code runs when the DOM is ready and creates a context object which is  
// needed to use the SharePoint object model
$(document).ready(function () {

    //Get the URI decoded URLs.  
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl"));
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl"));
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource
 
    advancedSearch.getattachment();
    // Load the js file and continue to load the page with information about the list top level folders.
    // SP.RequestExecutor.js to make cross-domain requests

    // Load the js files and continue to the successHandler
   
});
var advancedSearch = {
    getattachment: function () {
        var filterQuery = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getByTitle('crosslist')/items?$select=AttachmentFiles,Title&$expand=AttachmentFiles&@target='" + hostweburl + "'";
        advancedSearch.getFieldDetails(filterQuery,
                       function (data) {


                           var jsonObject = JSON.parse(data.body);
                           var results = jsonObject.d.results;

                           $.each(results, function (index, items) {//looping all the items
                               //Get Admin web url
                               var attchments = items.AttachmentFiles;
                               $.each(attchments.results, function (indx, attch) {//looping all the attachments
                                   var FileName1 = attch.FileName;
                                   var serverrelativeurl1 = attch.ServerRelativeUrl;
                                   getFileContent(serverrelativeurl1, FileName1);
                               });
                           });
                         
                           console.log(FileName);
                           console.log(serverrelativeurl);
                     
                       });
    },
    getFieldDetails: function (url, successHandler, errorHandler) {
        var executor;
        // Initialize the RequestExecutor with the app web URL.
        executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url: url,
            method: "GET",
            headers: {
                "Accept": "application/json; odata=verbose"
            },
            success: successHandler,          
            error: errorHandler
        });
    }
}

function getFileContent(serverrelativeurl,fileName)
{
    //var url=
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('"+serverrelativeurl+"')/$value?@target='" + hostweburl + "'",
        method: "GET",
        binaryStringResponseBody: true,
        success:
         function (data) {
             var fileContent = data.body;
             alert(fileContent);
  // once we have the file perform the actual upload
            execCrossDomainRequest(fileContent, fileName);
         
            },
            error:  function (err) {
                alert("error: " + err);
            }
   });
}


// Function to prepare and issue the request to get
//  SharePoint data
function execCrossDomainRequest(strfileContent, strFileName) {
   
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync(
    {
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('CustomList5')/items(2)/AttachmentFiles/add(FileName='" + strFileName + "')?@target='" + hostweburl + "'",
        method: "POST",
        processData: false,
        headers: {
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        contentType: "application/json;odata=verbose",
        binaryStringRequestBody: true,
        body: strfileContent,
        success: readContents,
        error: function (err) {
            alert('Oops! Document attached created fail.');
        }
    }
    );
}

function readContents(data) {
    alert(data.body.toString());
}
// Retrieve a query string value.  
// For production purposes you may want to use  
// a library to handle the query string.  
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}





Reference
http://techmikael.blogspot.in/2013/07/how-to-copy-files-between-sites-using.html

No comments:

Post a Comment