I would like to upload a zip file as part of formdata in a Javascript fetch. I can easily send in a zip file which I have read in via a file input control (see first segment of code). But when try to create a file object based on a blob, I receive an error (see second segment of code).
Basically I am asking how to create a zip file object from a blob. I tried many variations of code, but cannot nail the right syntax of creating the file object from blob, but it has to be a zip file. Note that the zip file is a shapefile - not sure if it makes any difference.
//here we upload the zip file
var fileInput = document.getElementById('avatar');
var filename = fileInput.files[0].name;
//and then I can easily send the zip file in formdata
var headers = new Headers();
headers.set('X-CSRFToken', csrftoken);
var formData = new FormData()
formData.set("time", false)
formData.set("base_file", fileInput.files[0] )
fetch("/upload/", {
"credentials": "include",
"body": formData,
"headers": headers,
"method": "POST",
"mode": "cors"
})
But when I try to upload zip file I created from a blob, then I receive an error
var shpBuffer = await ShapeFileFromGeoJSON(geojson, fileName);
var base64String = Uint8Array.from(window.atob(shpBuffer), (v) => v.charCodeAt(0));
var shapeFileBlob = new Blob([ base64String ], {type:"application/zip"});
saveAs(shapeFileBlob, fileName); //this works and a zip file is saved
var file = new File([shapeFileBlob], 'application.zip', { type: shapeFileBlob.type,});
console.log(file);
//Returns: "File {name: 'application.zip', lastModified: 1656002582746,
//lastModifiedDate: Fri Jun 24 2022 04:43:02 GMT+1200 (New Zealand Standard Time),
//webkitRelativePath: '', size: 6091726, …}"
console.log(file instanceof File); //returns true
var headers = new Headers();
headers.set('X-CSRFToken', csrftoken);
var formData = new FormData()
formData.set("time", false)
formData.set("file", file)
fetch("/upload/", {
"credentials": "include",
"body": formData,
"headers": headers,
"method": "POST",
"mode": "cors"
})
The error returned in the console is
POST https://WEBSITE/upload/ 400 (Bad Request)
{success: false, errors: Array(1)}