I have a list item with attachments. I want to copy this attachment to another item using JSOM or REST API. Anyone suggest an idea to do this.


The following code for your reference. Tested the code. its working

<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
var url = _spPageContextInfo.webAbsoluteUrl;
var listName="CL1120";
var sourceItemId=1;
var targetItemId=2;
function getAttachments() {   
    var requestUri = url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + sourceItemId + ")/AttachmentFiles";
    // execute AJAX request
    return $.ajax({
        url: requestUri,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" }       
function copyAttachments(){
            //var fileUrl=item.ServerRelativeUrl;
            var targetFileName=item.FileName;
            var sourceSiteUrlList = url + "/_api/web/lists/getbytitle('" + listName + "')/items("+sourceItemId+")/AttachmentFiles/getbyfilename('" + targetFileName + "')/$value";
            var targetSiteUrl = url + "/_api/lists/GetByTitle('" + listName + "')/items(" + targetItemId + ")/AttachmentFiles/add(FileName='" + targetFileName + "')";
            var xhr = new XMLHttpRequest();
            xhr.open('GET', sourceSiteUrlList, true);
            xhr.setRequestHeader('binaryStringResponseBody', 'true');
            xhr.responseType = 'arraybuffer';
            xhr.onload = function (e) {
                if (this.status == 200) {
                    var arrayBuffer = this.response;
                        url: targetSiteUrl,
                        method: 'POST',
                        data: arrayBuffer,
                        processData: false,
                        headers: { 'binaryStringRequestBody': 'true', 'Accept': 'application/json;odata=verbose;charset=utf-8', 'X-RequestDigest':  $('#__REQUESTDIGEST').val() }
                    }).done(function (postData) {
                            console.log('we did it!');
                    }).fail(function (jqXHR, errorText) {
    <input type="button" onclick="copyAttachments()" value="Copy Attachments"></input>
  • Thanks, this code is copying the attachments with the same name. but the file is not properly creating. if I have one .txt file with content means, new file have some XML content, not the same text content. - any idea about it. – PGP Nov 21 '19 at 4:39

Append $value at the end of the URL to get the file attachment

var sourceSiteUrlList = webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items("+sourceItemId +")/AttachmentFiles/getbyfilename('" + fileName + "')/$value";

This seems to fix the issue of corrupted files with non text files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.