0

I'm "developing" a SharePointlist which requires to upload two pdf files at the same time, I got this code on the internet:

function upload() {
// Define the folder path for this example.
var serverRelativeUrlToFolder = 'SiteAssets';

// Get test values from the file input and text input page controls.
var fileInput = jQuery('#attachmentId');
var newName = jQuery('#displayName').val();
var fileCount = fileInput[0].files.length;
// Get the server URL.
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
var filesUploaded = 0;
for(var i = 0; i < fileCount; i++){
    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer(i);
    getFile.done(function (arrayBuffer,i) {

        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer,i);
        addFile.done(function (file, status, xhr) {
            //$("#msg").append("<div>File : "+file.d.Name+" ... uploaded sucessfully</div>");
            filesUploaded++;
            if(fileCount == filesUploaded){
                alert("All files uploaded successfully");
                //$("#msg").append("<div>All files uploaded successfully</div>");
                $("#attachmentId").value = null;
                filesUploaded = 0;
            }
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);

}

// Get the local file as an array buffer.
function getFileBuffer(i) {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result,i);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(fileInput[0].files[i]);
    return deferred.promise();
}

// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer,i) {
var index = i;

    // Get the file name from the file input control on the page.
    var fileName = fileInput[0].files[index].name;

    // Construct the endpoint.
    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/lists/getfolderbyserverrelativeurl('{1}')/560" +
            "AttachmentFiles/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName);

            console.log(fileCollectionEndpoint);

    // Send the request and return the response.
    // This call returns the SharePoint file.
    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
        }
    });
}

}

I see it uploads to 'Site assets' folder, how can I change it to upload to my list item? I have little to no programming experience, so it's really hard to me to get this done.

I changed the URL line to /Lists/Pagamento//Attachments/ID/file.name but it didn't work.

This is how I'm getting the list ID:

function GetListItemId() {

  var context = new SP.ClientContext.get_current();
  var web = context.get_web();
  var list = web.get_lists().getByTitle('Pagamento');
  var query = SP.CamlQuery.createAllItemsQuery();
  allItems = list.getItems(query);
  context.load(allItems);
  context.executeQueryAsync(Function.createDelegate(this, this.successGetListItemId));
}

function successGetListItemId() {

  var ListEnumerator = this.allItems.getEnumerator();
  while (ListEnumerator.moveNext()) {
    var currentItem = ListEnumerator.get_current();
    TextFiled = currentItem.get_item('ID');
  }

  upload(TextFiled);

}

I'm calling the function GetListItemId() after I click the button save and the item is created, so there is no conflict if another user click the button at the same time.

function onQuerySucceeded() {
  GetItemListId();
  alert('Pagamento solicitado');
  window.location.assign('https://planet-uat.coface.dns/sites/teambrazil/_layouts/15/start.aspx#/Lists/Pagamento%20de%20conta%200001/AllItems.aspx');
}
4
  • hi check the var fileCount = fileInput[0].files.length;
    – Sunil Sahu
    Oct 10, 2018 at 8:56
  • Thanks again for you answer! I tried to use debugger from mozilla firefox and the code worked perfectly, but when I tried again without debugging I got the error "undefined" and only uploaded some of the items. Do you have any idea of what could it be?
    – Eddie
    Oct 10, 2018 at 13:54
  • It will be due to asynchronous behavior of java-script, try to implement deffered promises
    – Sunil Sahu
    Oct 10, 2018 at 14:09
  • I changed the code a little, then I received the error {"error":{"code":"-2130575305, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"Save Conflict.\n\nYour changes conflict with those made concurrently by another user. If you want your changes to be applied, click Back in your Web browser, refresh the page, and resubmit your changes."}}}. May this is happening because I create the item first, and then I get its ID and upload the file, but it still receive all except the last file.
    – Eddie
    Oct 10, 2018 at 19:29

2 Answers 2

0

You just need to change the endpoint or URL to upload in list against item id.

function upload() {
// Define the folder path for this example.
var serverRelativeUrlToFolder = 'Sample';

//change item to your itemid for no hardcoding the value
var itemId = 92;

// Get test values from the file input and text input page controls.
var fileInput = jQuery('#getFile');
// var newName = jQuery('#displayName').val();
var fileCount = fileInput[0].files.length;
// Get the server URL.
var serverUrl = _spPageContextInfo.webAbsoluteUrl;
var filesUploaded = 0;
for(var i = 0; i < fileCount; i++){
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(i);
getFile.done(function (arrayBuffer,i) {

    // Add the file to the SharePoint folder.
    var addFile = addFileToFolder(arrayBuffer,i);
    addFile.done(function (file, status, xhr) {
        //$("#msg").append("<div>File : "+file.d.Name+" ... uploaded sucessfully</div>");
        filesUploaded++;
        if(fileCount == filesUploaded){
            alert("All files uploaded successfully");
            //$("#msg").append("<div>All files uploaded successfully</div>");
            $("#getFile").value = null;
            filesUploaded = 0;
        }
    });
    addFile.fail(onError);
});
getFile.fail(onError);

}

// Get the local file as an array buffer.
function getFileBuffer(i) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
    deferred.resolve(e.target.result,i);
}
reader.onerror = function (e) {
    deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(fileInput[0].files[i]);
return deferred.promise();
}

// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer,i) {
var index = i;

// Get the file name from the file input control on the page.
var fileName = fileInput[0].files[index].name;

// Construct the endpoint.
var queryUrl = serverUrl+ "/_api/lists/GetByTitle('" + serverRelativeUrlToFolder + "')/items(" + itemId + ")/AttachmentFiles/add(FileName='" + fileName + "')";

// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
    url: queryUrl,
    type: "POST",
    data: arrayBuffer,
    processData: false,
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
        "content-length": arrayBuffer.byteLength
    }
});
}
}

// Display error messages. 
function onError(error) {
alert(error.responseText);
}
3
  • Thank you for your answer! It's working almost perfectly, just one problem: It doesn't upload the last file I selected, exemple: I selected 3 files, it will upload only two. What am I doing wrong? I edit my post to show you how i'm getting the list ID.
    – Eddie
    Oct 9, 2018 at 13:30
  • there is no snippet for file iteration in your question, please share you file iteration code for better understanding.
    – Sunil Sahu
    Oct 9, 2018 at 14:27
  • I edit the original question with the code to get the ID and how I'm calling it. Thanks!
    – Eddie
    Oct 9, 2018 at 14:42
0

You need to change this line:

var serverRelativeUrlToFolder = 'SiteAssets';

To

var serverRelativeUrlToFolder = 'YourLibraryName';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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