0

I am trying to upload document in "Attachment" column of SharePoint list. I am able to upload the document but not view the document. The SharePoint list is given below image:- enter image description here

When I am click on the "Attachment" column for view the document then not able to view the document. The error which is showing when I am click on that column is given in below image:- enter image description here

Here I am using below code for upload the document in "Attachment" column :-

function Submitbtn(event) {
var listName = "AttachementTestList"
var itemType = GetItemTypeForListName(listName);
var item = {
    "__metadata": { "type": itemType },
    "Title": $("#txtName").val(),
};

$.ajax({
    url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data) {
        var itemId = data.d.Id;
        var Path = $("#txtfile").val();
        var file = $("#txtfile").prop("files")[0];
        var uploadedfile = file.name;
        $.ajax
            ({
                url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles/add(FileName='" + uploadedfile + "')",
                type: "POST",
                data: JSON.stringify
                    ({
                        __metadata:
                        {
                            type: "SP.Data.AttachementTestListListItem"
                        },
                        Path: Path,
                    }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "X-HTTP-Method": "POST"
                },
                success: function (data) {
                    alert("Data Submitted Successfull");
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseJSON.error.message);
                }
            });
       
    },
    error: function (data) {

        console.log("not submitted");
    }
});

}

function GetItemTypeForListName(name) { return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem"; }

1 Answer 1

2

Ok, first, as a side note, I see you are using

_spPageContextInfo.siteAbsoluteUrl

to build your REST API URLs. I would highly recommend switching to use

_spPageContextInfo.webAbsoluteUrl

because siteAbsoluteUrl is going to give you the absolute URL of the root web in the Site Collection, so if you happen to be working in a sub-site within the site collection, you are not going to be getting the correct URL. webAbsoluteUrl will give you the correct URL for whatever sub-site you happen to be in.

Now, I see that you are constructing the correct URL to use to upload an attachment. If you have just created a new item there is a little shortcut you can take to get that URL, which I will show you.

The problem I'm seeing, though, is that to upload an attachment, you need to be sending an ArrayBuffer of the file as the data payload, not whatever object you are stringify-ing there in your second POST where you try to upload the attachment. On JavaScript File objects, there is a function arrayBuffer() you can call to get the ArrayBuffer to send.

So here's how I would adjust your code:

// create the new item, but switch to webAbsoluteUrl
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data) {
        // get the file
        var file = $("#txtfile").prop("files")[0];
        var uploadedFileName = file.name;

        // you can construct the upload URL the way that you were, this is fine
        var itemId = data.d.Id;
        var uploadUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles/add(FileName='" + uploadedFileName + "')";

        // but, an alternate way to construct it would be
        var alternateUploadUrl = data.d.AttachmentFiles.__deferred.uri + "/add('" + uploadedFileName + "')";

        // now we need to get an array buffer of the file
        file.arrayBuffer().then(function (arrayBuffer) {
            $.ajax({
                url: uploadUrl,
                type: "POST",
                data: arrayBuffer,
                processData: false, // this is important to not have jQuery interfere
                headers: {
                    // when uploading attachments these are the 
                    // only two headers i have ever needed to include,
                    // and you probably want to remove the Content Type
                    // header because the content type you are sending
                    // is now an ArrayBuffer and not JSON
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: function (data) {
                    alert("Data Submitted Successfull");
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseJSON.error.message);
                }
            });
        });
    },
    error: function (data) {
        console.log("not submitted");
    }
});
1
  • Thank you It is working for me
    – Shreya
    Aug 24, 2021 at 5:54

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.