3

I'm working on Office Add-in project, I need to get current Office file and upload to our server. Below is upload file from File Browser to our server

var fdata = new FormData();
fdata.append('data', file);
fdata.append('totalFileSizeBytes', file.size);
fdata.boundary = '----boundary';

xhr.send(fdata);

And I got Office file info via function: Document.getFileAsync (https://dev.office.com/reference/add-ins/shared/document.getfileasync)

But I don't know how to convert File info from Document.getFileAsync to FormData. I tried read File info slice by slice then concat to an array and pass to FormData, but it wasn't success.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Mục Đồng
  • 216
  • 1
  • 12

2 Answers2

6

The answer is a bit late, but hopefully might help future folks looking for this - I wasted some time trying to figure this out.

The File object returned by the Document.getFileAsync is not usable with FormData. Also what the Microsoft Documentation shows you does not get you a file that you can just drop into FormData.

First, you'll have to combine the slices returned to a docdata array as per the Microsoft example shows (https://learn.microsoft.com/en-us/javascript/api/office/office.document?view=office-js#getfileasync-filetype--options--callback-). But then instead of creating a string out of it by using charCodeAt, you'll want just use the combined docdata array and do this:

const file = new File(
  [new Uint8Array(docdata)], 
  'testfile.docx', 
  { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }
);

Which you can then proceed to append to your FormData:

const fd = new FormData();
fd.append('file', file);
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
Wingmen
  • 81
  • 3
  • 3
2

The new File() gave me an error. But the a new Blob() did the trick

var aFile = new Blob(
    [new Uint8Array(docdata)],
    { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }
);

formData.append('file', aFile, 'testfile.docx');
Forgeabc
  • 21
  • 1