Created
May 31, 2017 12:10
-
-
Save durgesh97025/eab8d998849c99a8d9217696e2dca9ae to your computer and use it in GitHub Desktop.
File Upload/Copy from another Http Url in SharePoint Online using REST and jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SourceList = "SourceList"; | |
var DestinationList = "DestinationList"; | |
$(document).ready(function() { | |
exec(); | |
$("#myBtn").click(exec); | |
}); | |
function exec() { | |
var sourceId = 12; | |
var sourceAttachmentUrl = _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('" + SourceList + "')/Items('" + sourceId + "')/Attachmentfiles"; | |
//var targetAttachmentUrl = _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + DestinationList + "')/items('" + 182 + "')/AttachmentFiles/add(FileName='{0}')"; | |
var targetAttachmentUrl = _spPageContextInfo.webServerRelativeUrl + "/_api/web/GetFolderByServerRelativeUrl('/sites/SM/Shared Documents')/Files/add(url='{0}',overwrite=true)"; | |
console.log(sourceAttachmentUrl); | |
$.getJSON(sourceAttachmentUrl, function(data) { | |
//console.log(data); | |
$.each(data.value, function(i, v) { | |
var fileUrl = v.ServerRelativeUrl; | |
var fileName = v.FileName; | |
//console.log(v); | |
var oReq = new XMLHttpRequest(); | |
oReq.onload = FileLoad; | |
oReq.open("GET", fileUrl, true); | |
oReq.responseType = "blob"; | |
oReq.send(); | |
function FileLoad(e) { | |
var blobData = oReq.response; //not responseText | |
var blob = new Blob([blobData]); | |
PostToDest(targetAttachmentUrl.replace('{0}', fileName), blob); | |
} | |
}); | |
}); | |
} | |
function PostToDest(url, bytes) { | |
return $.ajax({ | |
type: "POST", | |
url: url, | |
headers: { | |
"X-RequestDigest": $("#__REQUESTDIGEST").val(), | |
"binaryStringRequestBody": true, | |
"Accept": "application/json;odata=verbose;charset=utf-8" | |
//,"content-length": bytesLength | |
}, | |
processData: false, | |
data: bytes, | |
success: FileUploadSuccess, | |
error: FileUploadError | |
}); | |
function FileUploadSuccess(data, textStatus, request) { | |
//console.log("File uploaded successfully"); | |
var newfileUrl = data.d.ServerRelativeUrl; | |
$.get(newfileUrl, function(data, status, request) { | |
var bytesLength = request.getResponseHeader('content-length'); | |
console.log('Byte Length is ' + bytesLength); | |
}); | |
} | |
function FileUploadError(jqXHR, errorText) { | |
console.log(jqXHR); | |
console.log(errorText); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment