0

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.

1

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(){
    getAttachments().done(function(data){
        $.each(data.d.results,function(i,item){
            //var fileUrl=item.ServerRelativeUrl;
            var targetFileName=item.FileName;
            var sourceSiteUrlList = url + "/_api/web/lists/getbytitle('" + listName + "')/items("+sourceItemId+")/AttachmentFiles/getbyfilename('" + targetFileName + "')";
            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;
                    $.ajax({
                        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) {
                            //alert(errorText.statusText);
                    });
                }
            }
            xhr.send();         
        }); 
    }); 
}
</script>
<div>
    <input type="button" onclick="copyAttachments()" value="Copy Attachments"></input>
</div>
| improve this answer | |
  • 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

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.