none
Javascript Client Object Model OpenBinary Method? RRS feed

  • Question

  • Hello,

    Is there any way i can read document stream in javascript like we can call OpenBinary method in C#? Is there any replacement of SPFile.OpenBinary method? I have seen lot of samples for uploading documents to the document libary in JavaScript but no sample contains information about reading document stream from SharePoint.

    I want to create SharePoint hosted app to read the document from document library and send the Stream to REST service. As this is SharePoint hosted app, i have only option to use JavaScript for document handling.

    Regards,

    Muhammad Irfan Khan


    KhanG


    Monday, May 6, 2013 4:58 PM

Answers

All replies

  • You can use REST to get the binary. The following code is an example to use from the app model. But you can modify the REST url to use on-premises.

    hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
        appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
      
        fileContentUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/shared documents/year-end review format.docx')/$value?@target='" + hostweburl + "'";
        var fileContent = getBinary(fileContentUrl);
    
    function getBinary(sUrl) {
        var binaryData;
        $.support.cors = true;
        $.ajax(
                       {
                           url: sUrl,
                           method: "GET",
                           headers: {
                               "accept": "application/json; odata=verbose",
                           },
                           async:false,
                           success: function (data) {                                                         
                               binaryData = data;
                               },
                           error: function (err) {
                               alert(JSON.stringify(err));
                           },
                       }
                   );
    
        return binaryData;
    
    }


    Blog | SharePoint Field Notes Dev Tool | ClassMaster

    Tuesday, May 7, 2013 2:24 AM
  • Hello Steve.Curran,

    Thanks for great help. it worked. but now the problem is the returned value is not binary data it is some text. If i save the text as pdf on my local machine, adobe does not open the file and say it is currepted.

    I think i have covered 80% of the task and just the string/binary data returned format is problem now.

    Please help me so i can complete my assignment. Thanks a lot.

    Regards,

    Muhammad Irfan 


    KhanG

    Wednesday, May 8, 2013 2:17 PM
  • Hi,
    Did you resolve the encoding issue? I'm experiencing the same. When I look at the data coming back with Fiddler it looks correct, but the bytes seem off when I examine the data in the callback.

    Thanks,
    Mikael Svenson

    Search Enthusiast - SharePoint MVP/MCT/MCPD - If you find an answer useful, please up-vote it.
    http://techmikael.blogspot.com/
    Author of Working with FAST Search Server 2010 for SharePoint

    Tuesday, July 16, 2013 9:07 AM
  • I'll answer this myself :)

    Solution and code can be found at http://techmikael.blogspot.no/2013/07/how-to-copy-files-between-sites-using.html

    It's all about getting the parameters right in order to not mess up the encoding. I did not manage to do this using $.ajax, but had to use SP.RequestExecutor.

    Thanks,
    Mikael Svenson


    Search Enthusiast - SharePoint MVP/MCT/MCPD - If you find an answer useful, please up-vote it.
    http://techmikael.blogspot.com/
    Author of Working with FAST Search Server 2010 for SharePoint

    Wednesday, July 17, 2013 8:27 AM
  • Hello Mikael,

    i am facing same problem and with help of your blog i am unable to solve this with help of your blog. below is my code can you help me with this. 

    function SaveToDisk_blob(blobURL, fileName)
    {
        
        var reader = new FileReader();
        var blob = new Blob([blobURL.body], { type: "application/" + fileName.split(".")[1] + "" });
        window.navigator.msSaveBlob(blob, fileName);
    }
    
    function downloadFile(rest_url,filepath, fileName)
    {
        var dfd = $.Deferred();
        if (!window.ActiveXObject)
        {
            var save = document.createElement('a');
            save.href = filepath;
            save.target = '_blank';
            save.download = fileName || 'unknown';
    
            var event = document.createEvent('Event');
            event.initEvent('click', true, true);
            save.dispatchEvent(event);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
            dfd.resolve(true);
        }
        else if (!!window.ActiveXObject && document.execCommand)
        {
            var appweburl = _spPageContextInfo.webAbsoluteUrl
            $.getScript(appweburl + "/_layouts/15/SP.RequestExecutor.js", function () {
                var executor = new SP.RequestExecutor(appweburl);
                //if (requestInfo.binaryStringResponseBody) {
                //    responseInfo.body = xhr.response;
                //}
                executor.executeAsync(
                {
                    url: rest_url,
                    type: "GET",
                    binaryStringResponseBody: true,
                    success: function (blobURL)
                    {
                        SaveToDisk_blob(blobURL, fileName)
                        dfd.resolve(true);
                    },
                    error: function (xhr)
                    {
                        console.log(xhr);
                        dfd.reject();
                    }
                });
            });
        }
        return dfd.promise()
    }
    
    function call_to_rest_binarystring(rest_url)
    {
        var ajax_call = $.ajax({
            url: rest_url,
            method: "GET",
            binaryStringResponseBody: true,
            headers:
                {
                    "accept": "application/json; odata=verbose"
                },
        });
        return ajax_call;
    }
    
    the file which is download after this, it gets corrupted. 

    Thursday, April 2, 2015 11:36 AM