4

I am trying to add file to document library by using REST IN SP 2013 APP MODEL.

This is my code I can upload file to document library but I can't add items value to that document library in fields please look this code help me find the issue. I'm getting the error at getItem(file){}

function uploadDocument() {



            var params = document.URL.split("?")[1].split("&");
            for (var i = 0; i < params.length; i = i + 1) {
                var param = params[i].split("=");
                switch (param[0]) {
                    case "SPAppWebUrl":
                        appWebUrl = decodeURIComponent(param[1]);
                        appweburl = decodeURIComponent(param[1]);
                        //alert(appWebUrl);
                        break;
                    case "SPHostUrl":
                        targetSiteUrl = decodeURIComponent(param[1]);
                        hostUrl = decodeURIComponent(param[1]);

                        //alert(targetSiteUrl);
                        break;
                }
            }





            if (!window.FileReader) {
                alert("This browser does not support the HTML5 File APIs");
                return;
            }

            var element = document.getElementById("uploadInput");
            var file = element.files[0];
            var parts = element.value.split("\\");
            var fileName = parts[parts.length - 1];

            var reader = new FileReader();
            reader.onload = function (e) {
                addItem(e.target.result, fileName);
            }
            reader.onerror = function (e) {
                alert(e.target.error);
            }
            reader.readAsArrayBuffer(file);

            function addItem(buffer, fileName) {
                alert('asdsasadsa');
                var call = uploadDocument(buffer, fileName);
                call.done(function (data, textStatus, jqXHR) {
                    alert('call.done');
                    alert(data.d);
                    var call2 = getItem(data.d);
                    call2.done(function (data, textStatus, jqXHR) {
                        var item = data.d;
                        alert(item);
                        var call3 = updateItemFields(item);
                        call3.done(function (data, textStatus, jqXHR) {
                            var div = jQuery("#message");
                            div.text("Item added");
                        });
                        call3.fail(function (jqXHR, textStatus, errorThrown) {
                            failHandler(jqXHR, textStatus, errorThrown);
                        });
                    });
                    call2.fail(function (jqXHR, textStatus, errorThrown) {
                        failHandler(jqXHR, textStatus, errorThrown);
                    });
                });
                call.fail(function (jqXHR, textStatus, errorThrown) {
                    failHandler(jqXHR, textStatus, errorThrown);
                });
            }

            function uploadDocument(buffer, fileName) {
                alert('hi this is uploaddoc');
                alert(appWebUrl);
                var libraryName = 'Documents';

                var url = appWebUrl + "/_api/SP.AppContextSite(@TargetSite)/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?"+
                "@TargetSite='" + targetSiteUrl + "'" +
            "&@TargetLibrary='" + libraryName + "'" +
            "&@TargetFileName='" + 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) {
                alert(file);
                alert('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) {
                alert('updateItemFields');
                alert(item.Id);
                var now = new Date();
                var call = jQuery.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl +
                        "/_api/Web/Lists/getByTitle('Documents')/Items(" +
                        item.Id + ")",
                    type: "POST",
                    data: JSON.stringify({
                        "__metadata": { type: "SP.Data.DocumentsItem" },
                        Title: 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;
            }

            function failHandler(jqXHR, textStatus, errorThrown) {
                var response = JSON.parse(jqXHR.responseText);
                var message = response ? response.error.message.value : textStatus;
                alert("Call failed. Error: " + message);
            }
        }
  • so does this getItem method work ? Do you get the exact Item? – Gwny Jun 11 '14 at 12:20
1

I have test your code and I came to a conclusion:

As you are developing your app, you need to declare instance of the site context, each time you make an ajax request, try to use the cross-domain, because you are trying to access or post data out of the APP, if you do not will always get those errors.

Developed a trivial solution, follows the code below:

'use strict';

var appWebUrl, appweburl, targetSiteUrl, hostUrl;

function uploadDocument() {

var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
    var param = params[i].split("=");
    switch (param[0]) {
    case "SPAppWebUrl":
        appWebUrl = decodeURIComponent(param[1]);
        appweburl = decodeURIComponent(param[1]);
        //alert(appWebUrl);
        break;
    case "SPHostUrl":
        targetSiteUrl = decodeURIComponent(param[1]);
        hostUrl = decodeURIComponent(param[1]);

        //alert(targetSiteUrl);
        break;
    }
}

if (!window.FileReader) {
    alert("This browser does not support the HTML5 File APIs");
    return;
}

var element = document.getElementById("uploadInput");
var file = element.files[0];
var parts = element.value.split("\\");
var fileName = parts[parts.length - 1];

var reader = new FileReader();
reader.onload = function(e) {
    addItem(e.target.result, fileName);
}
reader.onerror = function(e) {
    alert(e.target.error);
}
reader.readAsArrayBuffer(file);

function addItem(buffer, fileName) {
    alert('asdsasadsa');
    var call = uploadDocument(buffer, fileName);
    call.done(function(data, textStatus, jqXHR) {
        alert('call.done');
        alert(data.d);
        var call2 = getItem(data.d);
        call2.done(function(data, textStatus, jqXHR) {
            var item = data.d;
            updateItemFields(item);
        });
        call2.fail(function(jqXHR, textStatus, errorThrown) {
            failHandler(jqXHR, textStatus, errorThrown);
        });
    });
    call.fail(function(jqXHR, textStatus, errorThrown) {
        failHandler(jqXHR, textStatus, errorThrown);
    });
}

function uploadDocument(buffer, fileName) {

    var libraryName = 'Documents';

    var url = appWebUrl + "/_api/SP.AppContextSite(@TargetSite)/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?" + "@TargetSite='" + targetSiteUrl + "'" + "&@TargetLibrary='" + libraryName + "'" + "&@TargetFileName='" + 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 callURL = convertURLCrossDomain(file.ListItemAllFields.__deferred.uri);
    var call = jQuery.ajax({
        url: callURL,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });

    return call;
}

function updateItemFields(item) {                       
    var callitemType = getItemTypeForListName('Documents');
    callitemType.done(function(itemType) {
        var callURL = convertURLCrossDomain(_spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Documents')/Items(" + item.Id + ")");
        var nowString = new Date().getFullYear().toString();
        var itemJSON = {
            "__metadata": {
                "type": itemType.d.ListItemEntityTypeFullName
            },
            "Title": nowString
        };
        var call = jQuery.ajax({
            url: callURL,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(itemJSON),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": item.__metadata.etag
            }
        });
        call.done(function() {
            var div = jQuery("#message");
            div.append("Item added sucess!");
        });
        call.fail(function() {
            var div = jQuery("#message");
            div.append("Item added failed");
        });
    });
    callitemType.fail(function(result) {
        failHandler(result, "", "");
    });
}


function failHandler(jqXHR, textStatus, errorThrown) {
    var response = JSON.parse(jqXHR.responseText);
    var message = response ? response.error.message.value : textStatus;
    alert("Call failed. Error: " + message);
}

/*
    Function convertURLCrossDomain created by b1c10 all right reserved
*/
function convertURLCrossDomain(url) {
    var urlsplitted = url.split('/');
    var newURL = "";
    var startwrite = false;
    for (var i = 0; i < urlsplitted.length; i++) {
        if (urlsplitted[i].toLowerCase() == "_api") {
            newURL += appWebUrl + "/_api/";
            startwrite = true
        } else if (urlsplitted[i].toLowerCase() == "web") newURL += "SP.AppContextSite(@TargetSite)/web/"
        else if ((i + 1) == urlsplitted.length) {
            if (urlsplitted[i].indexOf("?") > -1) {
                newURL += urlsplitted[i] + "&@TargetSite='" + targetSiteUrl + "'";
            } else {
                newURL += urlsplitted[i] + "?@TargetSite='" + targetSiteUrl + "'";
            }
        } else if (startwrite) newURL += urlsplitted[i] + "/";
    }
    return newURL;
}

function getItemTypeForListName(name) {
    var call = $.ajax({
        url: convertURLCrossDomain("_api/web/lists/getbytitle('" + name + "')?$select=ListItemEntityTypeFullName"),
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        },
    });
    return call;
    //this return "SP.Data.listnameItems" but not is the correct then i have created method to prevent error in update item;
}

}

And other, with that your code had problems updating the list item. and had to restructure, tested for me and work fine :)

Regarding your code added two methods: convertURLCrossDomain (Url); getItemTypeForListName (ListName);

Hope this help.

Thanks.

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.