HTTP Uploads
Browsers and other platforms offer solutions for uploading files to servers and cloud storage solutions. Spreadsheets can be written using SheetJS and uploaded.
This demo explores file uploads using a number of browser APIs and wrapper libraries. The upload process will generate a sample XLSX workbook, upload the file to a test server, and display the response.
This demo focuses on uploading files. Other demos cover other HTTP use cases:
- "HTTP Downloads" covers downloading files
- "HTTP Server Processing" covers HTTP servers
Third-party cloud platforms such as AWS may corrupt raw binary uploads by encoding requests and responses in UTF-8 strings.
For AWS, in the "Binary Media Types" section of the API Gateway console, the
"multipart/form-data"
type should be added to ensure that AWS Lambda functions
can receive uploads from clients.
Uploading Binary Data
The SheetJS write
method1 generates file data stored in ArrayBuffer
objects. The ArrayBuffer
can be added to a FormData
object. The FormData
object can be passed along to POST requests.
Generating Files
In a typical scenario, a process generates arrays of simple objects.
The SheetJS json_to_sheet
method2 generates a SheetJS worksheet object3.
The book_new
method4 creates a workbook object that includes the worksheet.
The write
method5 generates the file in memory.
The following snippet creates a sample dataset and generates an ArrayBuffer
object representing the workbook bytes:
/* create sample SheetJS workbook object */
var aoa = [
["S", "h", "e", "e", "t", "J", "S"],
[ 5, 4, 3, 3, 7, 9, 5]
];
var ws = XLSX.utils.aoa_to_sheet(aoa);
var wb = XLSX.utils.book_new(ws, "Sheet1");
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
/* export SheetJS workbook object to XLSX file bytes */
var data = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
Creating Form Data
File
objects represent files. The File
constructor accepts an array of data
fragments and a filename.
Browser APIs typically represent form body data using FormData
objects. The
append
method adds fields to the FormData
object. Adding File
objects
effectively "attaches" a file in the upload.
The following snippet constructs a new FormData
object. The file
field in
the form will be set to the data from the previous snippet:
/* create File */
var file = new File([data], 'sheetjs.xlsx')
// generated XLSX ^^^^ ^^^^^^^^^^^^ file name
/* build FormData with the generated file */
var fdata = new FormData();
fdata.append('file', file);
// ^^^^ field name in the form body