2

This question already has an answer here:

What is the problem with this? Im trying to attach file in SharePoint.This is the error when I submit the attachment file

<!DOCTYPE html>
<html>
<head>
    <title>Sample</title>

        <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
        <script type="text/javascript" src="/_layouts/15/sp.js"></script>
        <script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>

        <script type="text/javascript" src="/SiteAssets/Sample/jquery-1.8.2.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/Sample/jquery-ui.js"></script>

        <script type="text/javascript" src="/SiteAssets/Sample/jquery.msgBox.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/Sample/jquery.multifile.js"></script>

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

    // 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 fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // 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(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}
</script>

</head>
<body>

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

</body>
</html>

marked as duplicate by Gaurravs, Karthik Jaganathan, MHeld, Mohamed El-Qassas MVP Aug 24 '18 at 15:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Yes to list/Library. – junreyd Aug 22 '18 at 6:00
  • In the List please need some help with regards to this. – junreyd Aug 22 '18 at 6:24
  • the above code upload file in library and you are trying for List. – Sunil Sahu Aug 22 '18 at 6:26
  • Yes I use that as my reference, can you give me idea how to do that one to attach the file and upload to the list? – junreyd Aug 22 '18 at 6:30
1

For upload attachment to list you need to change the script as the above script is for library,changing addFileToFolder

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);
}
  • 1
    you need to view item with Id=1 the attachment will be shown there. – Sunil Sahu Aug 22 '18 at 8:56
  • 1
    can share your item view for item id =1 – Sunil Sahu Aug 22 '18 at 9:03
  • I put the error and my code below please check where is the issue. – junreyd Aug 23 '18 at 0:23
0

How to add attachment including these list. My problem is how can I change the var itemId = (The ID of a list I add). From the code below.

Here is my code.

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

//change item to your itemid for no hardcoding the value
var itemId = (The ID of a list I add);

// 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);

}
  • 1
    Thanks, i have updated the answer run the script and share item view form for 92 – Sunil Sahu Aug 23 '18 at 8:52
  • 1
    now it working and you are able to see document – Sunil Sahu Aug 23 '18 at 9:00
  • @Junreyd : always edit question to extend your questions don't put it in answer. – Bhaskar Dhone Aug 24 '18 at 2:37
  • i think the answer to first question was complete but still it not mark as answer. Hope you mark it answer and ask your query as different question thread. – Sunil Sahu Aug 24 '18 at 5:35

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