4

I'm trying to get and save files from SharePoint app using REST, the files are located inside the host SP.

Once got the file, I'm saving/downloading it into the browser with a save function.

When I download a .txt, I get file and contents downloaded and saved. When I download a .pdf or .doc I get a file but once saved the content is empty. The new created file as the correct extension a size but it's like I'm not getting the correct binary for .pdf and .doc files, any suggestion?

Here is my code:

var prepareUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('" + filePath + "')/$value?@target='" + hostweburl + "'";

// executes cross domain request
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
{
url: prepareUrl,
type: "GET",
binaryStringResponseBody: true,
success: function (data) { readContentsAndSendToIAG(data, fileName) },
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText)
}
});
}

function readContentsAndSendToIAG(data, fileName) {
var blob = new Blob([data.body], { type: "application/pdf" });
saveAs(blob, fileName);

Thanks.

1

Solution found here, paslatek's comment: http://techmikael.blogspot.de/2013/07/how-to-copy-files-between-sites-using.html?showComment=1407787676122

The problem is that the Microsoft SP.RequestExecutor.js is doing this conversion:

if (requestInfo.binaryStringResponseBody) {
     responseInfo.body = SP.RequestExecutorInternalSharedUtility.BinaryDecode(xhr.response);
  }

but decoding the xhr.response, responseInfo.body is not more binary...

Solution is to patch JavaScript SP.RequestExecutor.js changing the if condition this way:

$.getScript(scriptbase + "SP.RequestExecutor.js", function(){
   //insert all the content of the original SP.RequestExecutor.js
   //until here
    if (requestInfo.binaryStringResponseBody) {
        responseInfo.body = xhr.response; 
     }

   //add the remaining original code
});

As you can see now the if condition becomes:

responseInfo.body = xhr.response; 

Now data.body contains binary data and can be used as I needed to create a Blob

var blob = new Blob([data.body], { type: "application/pdf" });
saveAs(blob, fileName);
  • You should really add the important part about the answer to your post here. I mean, if the link breaks it will be of no help to future readers – Robert Lindgren Aug 12 '14 at 11:22
  • Done, hope it helps – Roberto Mereu Aug 12 '14 at 14:56

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.