1

I am trying to upload file to SharePoint 2013 on-premise through REST API. Below is my main function

In below function it always throw error, I tried with getScript but it never goes inside the getScript then I added SP.RequestExecutor.js into my header but it throw error. Very few time it get succeeded and uploaded. Please help me on this.

function uploadFileHolder(listName, id, file) {
    var deferred = $.Deferred();
    var fileName = file.name;
    getFileBuffer(file).then(
            function (buffer) {
                var bytes = new Uint8Array(buffer);
                var binary = '';
                for (var b = 0; b < bytes.length; b++) {
                    binary += String.fromCharCode(bytes[b]);
                }
                console.log(' File size:' + bytes.length);
                //$.getScript("http://darwaza.kuwaitairways.com/_layouts/15/SP.RequestExecutor.js", function () {
                var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
                createitem.executeAsync({
                    url: "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                    method: "POST",
                    binaryStringRequestBody: true,
                    body: binary,
                    success: fsucc,
                    error: ferr,
                    state: "Update"
                });
                function fsucc(data) {
                    console.log(data + ' uploaded successfully');
                    deferred.resolve(data);
                }
                function ferr(data, args, errorMessage) {
                    console.log('error\n\n' + data.statusText + "\n\n" + data.responseText);
                    deferred.reject(data);
                }
                //});
            },
            function (err) {
                deferred.reject(err);
            }
    );
    return deferred.promise();
}
1

$.getscript is asynchronous call so it won't register immediately inside the page. So you have to make the $.getscript call synchronous. Like below,

 $.ajaxSetup({ async: false });
 $.getScript('<your_script_url>');
 $.ajaxSetup({ async: true });

else, you can run your code once the $.getscript execution is completed.Like below,

$.getScript(script_url).done(function(){
        //  Unrelated stuff here
        // do something with $element after the script loaded.
});

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.