3

I am trying to update attachment of list item using REST API. I am getting the below error:

{"error":{"code":"-2130575257, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The specified name is already in use.\n\nThe document or folder name was not changed. To change the name to a different value, close this dialog and edit the properties of the document or folder."}}}

I am using the below code to update list item:

function saveFile(fileArrBuffer, fileName, itemId) {
    var deferred = $q.defer();
    $http({
        method: 'POST',
        url: _spPageContextInfo.webServerRelativeUrl + '/_api/web/lists/getbytitle(\'' + 'EmployeeList' + '\')/items(' + itemId + ')/AttachmentFiles/add(FileName=\'' + fileName + '\')',
        headers: {
            'Accept': 'application/json;odata=verbose',
            'Content-Type': undefined,
            'X-RequestDigest': spContext.securityValidation,
        },
        data: new Uint8Array(fileArrBuffer),
        transformRequest: []
    }).then(function successCallback(data) {
        deferred.resolve(data);
        console.log('Successfully saved.', data, false);
    }, function errorCallback(error) {
        deferred.reject(error);
        console.log('Failed to save!!!.', error, false);
    });
    return deferred.promise;
}

I even tried to use overwrite=true inside the rest url but I got error saying that property overwrite is not supported.

3 Answers 3

4

Unfortunately there is no API to overwrite the list attachment, so you need to delete the attachment first before uploading it.

Try the below sample code:

function checkFileExists(){
    $.ajax({
            url: "https://sitecollectionurl/_api/web/getFileByServerRelativeUrl('/sitecollectionurl/Lists/Test/Attachments/1/test.txt')",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if(data.d.Exists){  
            //delete file if it already exists
                    DeleteFile();
                }
            },
            error: function (data) {
//check if file not found error
                AddAttachments();               
            }
      });
}
function DeleteFile(){
    $.ajax({
      url: "https://sitecollectionurl/_api/web/getFileByServerRelativeUrl('/sitecollectionurl/Lists/Test/Attachments/1/test.txt')",
      method: 'DELETE',
      headers: {
        'X-RequestDigest': document.getElementById("__REQUESTDIGEST").value
        },
      success: function (data) {            
            AddAttachments();
        },
        error: function (data) {
            console.log(data);      
        }
    });
}

function AddAttachments()
{   
    var digest = "";
    $.ajax(
    {
                    url: "/_api/contextinfo",
                    method: "POST",
                    headers: {
                                    "ACCEPT": "application/json;odata=verbose",
                                    "content-type": "application/json;odata=verbose"
                    },
                    success: function (data) {
                    digest = data.d.GetContextWebInformation.FormDigestValue;
                    },
                    error: function (data) {

                    }
    }).done(function() {
                    var fileInput = $('#uploadFile');
                    var fileName = fileInput[0].files[0].name;
                    var reader = new FileReader();
                    reader.onload = function (e) {
                    var fileData = e.target.result;
                        var res11 = $.ajax(
                        {                             
                                        url: "/sitecollectionurl/_api/web/lists/getbytitle('Test')/items(1)/AttachmentFiles/add(FileName='" + fileName + "')",                                       
                                        method: "POST",
                                        binaryStringRequestBody: true,
                                        data: fileData,
                                        processData: false,
                                        headers: {
                                                        "ACCEPT": "application/json;odata=verbose",          
                                                        "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                                                        "content-length": fileData.byteLength
                                        },                                                                                                                            
                                        success: function (data) {                                            
                                                console.log("success");                                               
                                        },
                                        error: function (data) {                                                
                                                console.log("Error occured." + data.responseText);
                                        }
                        });                          
                    };
                    reader.readAsArrayBuffer(fileInput[0].files[0]);

    });                                          
}

HTML:

 <input id="uploadFile" type="file">

<a onclick="checkFileExists()" value="Add Attachments">Add Attachment </a>
1
  • Thanks for the reply. Delete and uploading is working. Hopefully Microsoft will add update to the Rest API in future versions of SharePoint Commented Dec 27, 2016 at 4:10
0

I have done upload file to List attachment using Rest is something like this and it is working perfectly for me.

$(document).ready(function () 
{
var itemID = 1;

//Reading the Uploaded file values

var parts = document.getElementById("fileUpload").value.split("\\");

var filename = parts[parts.length - 1];

var file = document.getElementById("fileUpload").files[0];

uploadFileSP("TestList", itemID, filename, file);
}

function getFileBuffer(file) {

    var deferred = $.Deferred();

    var reader = new FileReader();

    reader.onload = function (e) {

        deferred.resolve(e.target.result);

    }

    reader.onerror = function (e) {

        deferred.reject(e.target.error);

    }

    reader.readAsArrayBuffer(file);
    return deferred.promise();

}

    //Used to Add Attachemnt to List Item

function uploadFileSP(listName, id, fileName, file) {

    var deferred = $.Deferred();

    getFileBuffer(file).then(

        function (buffer) {

            var bytes = new Uint8Array(buffer);

            var content = new SP.Base64EncodedByteArray();

            var queryUrl = web.get_url() + "/_api/web/lists/getbytitle('" + listName + "')/items(" + id +

             ")/AttachmentFiles/add(FileName='" + file.name + "')";

              $.ajax({

                  url: queryUrl,

                  type: "POST",

                  processData: false,

                  contentType: "application/json;odata=verbose",

                  data: buffer,

                  headers: {

                      "accept": "application/json;odata=verbose",

                      "X-RequestDigest": $("#__REQUESTDIGEST").val(),

                      "content-length": buffer.byteLength

                  }, success: function(result)
                            {
                                alert("Uploaded Successful");
                            },

                  error: function(result){console.log("Attachment Failure");}

              });

          },

            function (err) {

                deferred.reject(err);

            });

    return deferred.promise();

}
1
  • Thanks for the reply but I want to update the existing attachment, not upload a new attachment Commented Dec 26, 2016 at 10:42
0

I am not pretty sure about this, because I didn't try with attachments, but I guess if you do something like files API...

Try with overwrite="true" parameter

try this URL:

url: _spPageContextInfo.webServerRelativeUrl + '/_api/web/lists/getbytitle(\'' + 'EmployeeList' + '\')/items(' + itemId + ')/AttachmentFiles/add(FileName=\'' + fileName + '\', overwrite=\'true\')',
1
  • Hi. I tried it but I got error saying that property overwrite is not supported. Commented May 18, 2017 at 6:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.