Read Sharepoint Document Library file with JS FileReader API

2.2k Views Asked by At

I see other versions of this question that don't provide a Javascript solution. Can someone create one for this? I'm banging my head against the wall trying to get this to work.

So my overall scope is to copy a file, then put it in another document library, but I'm having trouble just reading the file. This is my best attempt so far...

function createAPinSPListOld(name,system,start,duration) {

    var binary = "";   
    var srcUrl = can't show this;
    var destURL = can't show this either; 

    // create metadata
    var data = { 
        __metadata: {'type': 'SP.Data.NXE_x0020_AP_x0020_TrackerItem'},
        System: system,
        Planned_x0020_Start: start,
        Required_x0020_Time_x0020__x0028_hrs_x0029_: duration,
    };

    $().SPServices({
        operation: "GetItem",
        Url: srcUrl,
        completefunc: function (xData, Status) {                    
            binary = $(xData.responseXML).find("Stream").text(); 
            console.log(xData);                                      
            console.log(binary);                                      
            // create item in SP list
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('NXE Action Plan Tracker')/rootfolder/files/add(url="+name+",overwrite=true)",
                type: "POST",
                body: binary,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "content-type": "application/json;odata=verbose",
                    "content-length":500000
                },
                data: JSON.stringify(data),
                success: function (data) {
                    console.log("Created successfully!")
                },
                error: function (error) {
                    alert("cannot add for some reason");
                    alert(JSON.stringify(error));
                }
            }); 
        }
    });
}
1

There are 1 best solutions below

6
Pradip Sukale On

Use the xhr to read document into byte array by using following function:

function ReadDocument(documentUrl) {
        try {
            if (documentUrl) {
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function (data) {
                        if (this.readyState == 4 && this.status == 200) {
       var fileData = this.response;
                        }
                    }
                    xhr.open('GET', documentUrl, true);
                    xhr.responseType = 'blob';
                    xhr.send();
            }
        } catch (e) {
            console.log(e);
        }
    }

Also I would recommend not to use SPService library as it is third party library and most of the feature that are available in this library are available in REST api.