8

Can somebody help me connect the dots between these functions. I can upload, but how do I get the ID of the file I just uploaded to update metadata columns on the File in the host Document Library?

Many Thanks!

function uploadDocument(buffer, fileName) {
    var url = String.format("{0}/_api/Web/Lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)",
        _spPageContextInfo.webAbsoluteUrl, fileName);

    var call = jQuery.ajax({
        url: url,
        type: "POST",
        data: buffer,
        processData: false,
        headers: {
            Accept: "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "Content-Length": buffer.byteLength
        }
    });

    return call;
}

function getItem(file) {
    var call = jQuery.ajax({
        url: file.ListItemAllFields.__deferred.uri,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });

    return call;
}

function updateItemFields(item) {
    var now = new Date();
    var call = jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl +
            "/_api/Web/Lists/getByTitle('Project Documents')/Items(" +
            item.Id + ")",
        type: "POST",
        data: JSON.stringify({
            "__metadata": { type: "SP.Data.Project_x0020_DocumentsItem" },
            CoordinatorId: _spPageContextInfo.userId,
            Year: now.getFullYear()
        }),
        headers: {
            Accept: "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "IF-MATCH": item.__metadata.etag,
            "X-Http-Method": "MERGE"
        }
    });

    return call;
}
Hell.Bent
  • 1,667
  • 9
  • 38
  • 73

1 Answers1

11

Add "?$expand=ListItemAllFields" to the url in your uploadDocument function. So

var url = String.format("{0}/_api/Web/Lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)", _spPageContextInfo.webAbsoluteUrl, fileName);

will become

var url = String.format("{0}/_api/Web/Lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)?$expand=ListItemAllFields", _spPageContextInfo.webAbsoluteUrl, fileName);

In the success/complete function of the returned ajax call you should now have access to the fields of the listItem associated with the newly created file. The following is an example.

$(document).ready(function () {
    uploadDocument(toUrl, FileName, binary, function (file) {
        updateItemFields(file.ListItemAllFields, function(){
            alert("Updated Succeeded");
        }, function(){
            alert("Update Failed");
        });
    }, function(error){
            alert(error);
    });
}

function uploadDocument(url, fileName, arrayBuffer, complete, failure) {
    $.ajax({
        url: url + "/_api/web/lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='" + fileName + "', overwrite=true)?$expand=ListItemAllFields",
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "Accept": "application/json; odata=verbose",
            "content-length": arrayBuffer.length,
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function (data) {
                complete(data.d);
        },
        error: function (err) {
            failure(err);
        }
    });
}

function updateItemFields(item, complete, failure) {
    var now = new Date();
    jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Project Documents')/Items(" + item.Id + ")",
        type: "POST",
        data: JSON.stringify({
            "__metadata": { type: "SP.Data.Project_x0020_DocumentsItem" },
            CoordinatorId: _spPageContextInfo.userId,
            Year: now.getFullYear()
        }),
        headers: {
            Accept: "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "IF-MATCH": item.__metadata.etag,
            "X-Http-Method": "MERGE"
        },
        success: function (data) {
            complete(data.d);
        },
        error: function (err) {
            failure(err);
        }
    });
}
Aubie2
  • 303
  • 3
  • 12
  • That doesn't appear to do anything for me :(. Really struggling to find the associated item id for a MS.FileServices.File – letstango Jul 10 '14 at 21:45
  • You are a life saver. Using the OData expand works a treat -- but you have to make another request for the file info and not directly on the upload request – letstango Jul 10 '14 at 23:04
  • Don't know if it's a typo or if it was changed, but I had to append 'ListItem' to the Library name in the metadata type, i.e 'SP.Data.Project_x0020_DocumentsListItem' instead of just 'Item'. Other than that it worked like a charm. – TMan May 28 '15 at 09:20
  • 1
    var addedFileId = data.d.ListItemAllFields.ID; – Gennady G May 14 '17 at 11:27