-1

Is it posible to upload file in Lists Attachments in SharePoint in custom way I already tried using REST and JS but I am facing an error and it can't upload if it's posible kindly suggest what way to do, if it's not posible I change the flow of my custom lists.

***Alert message error***

***Console error***

Here is the code I am using.

<script type="text/javascript">
function upload() {
// Define the folder path for this example.
var serverRelativeUrlToFolder = 'Sample';

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

// 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 + "')/Attachments(" + itemId + ")/Attachments/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);
}


</script>
<input id="getFile" name="file" type="file" multiple /><br />
<input id="addFileButton" type="button" value="Upload" onclick="upload();"/>

***This is the URL:***

  • Check your query. When you get list after that you gave attachements. You need to have items over there. as below var queryUrl = serverUrl+ "/_api/lists/GetByTitle('" + serverRelativeUrlToFolder + "')/Items(" + itemId + ")/Attachments/add(FileName='" + fileName + "')" – Bhaskar Dhone Aug 23 '18 at 4:56
  • Yes its possible and i think the way you are doing also correct.I suspect "serverRelativeUrlToFolder" should be a List Name and ItemID =1 should exists in that List. So its your end point URL is not formatted correctly – vinit kumar Aug 23 '18 at 4:59
  • @vinitkumar could you elaborate which part I had missing the format – junreyd Aug 23 '18 at 5:04
  • @BhaskarDhone still have this alert error {"error":{"code":"-2147024809, System.ArgumentException","message":{"lang":"en-US","value":"Item does not exist. It may have been deleted by another user."}}} – junreyd Aug 23 '18 at 5:05
  • It means Item with id 1 does not exists in the list 'Sample'. Check if it exists or not. – Bhaskar Dhone Aug 23 '18 at 5:06
1

If you want to upload file to list attachment it has to be associated with list item. Change your url as below :

 var queryUrl = serverUrl+ "/_api/lists/GetByTitle('" + serverRelativeUrlToFolder + "')/Items(" + itemId + ")/Attachments/add(FileName='" + fileName + "')";

I consider in 'Sample' as your list name and item id '1' is your existing item. If not not then you can give id of existing item. I will upload files to that list item as attachments.

For reference

  • If I change to Items this alert.. {"error":{"code":"-2147024809, System.ArgumentException","message":{"lang":"en-US","value":"Item does not exist. It may have been deleted by another user."}}} .. because I want to store the uploaded files into Attachment Column. – junreyd Aug 23 '18 at 6:44
  • your requirement is not clear.Based on above question and shared code. You were uploading file to list item as attachment. Please ask proper question on your query. – Bhaskar Dhone Aug 23 '18 at 6:48
  • 1
    I saw your query. Above code does exactly the same. You have to give item id of that item (eg. where comment is 'How to do this). and It will upload file to attachments. – Bhaskar Dhone Aug 23 '18 at 7:02

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.