I am working on a web application (using JQuery version 2.2.4) that allows users to submit images and data to our server. When users decide to upload their submissions, my code should generate a zip file using the JSZip library and upload it to our server using POST. After some searching here on StackExchange, I came up with this code:
var zip = new JSZip(); // Create the object representing the zip file
// ...Add the data and images
console.log('Generating compressed archive...');
zip.generateAsync({
compression: 'DEFLATE',
type: 'blob'
}).then(function(zc) {// Function called when the generation is complete
console.log('Compression complete!');
// Create file object to upload
var fileObj = new File([zc], fileName);
console.log('File object created:', fileObj);
$.post('http://myurl/submit', {
data: fileObj,
}).done(function() {
console.log('Ajax post successful.');
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Ajax post failed. Status:', textStatus);
console.log(errorThrown);
});
});
My code prints the File object created message, the file object itself looks OK, but then I get nothing else. A silent failure. The POST call does not even appear in the Net panel for Firebug.
After more searching, I also tried to add this code beforehand:
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
console.log('Ajax post failed. Event:', event);
console.log('Ajax settings:', settings);
console.log(thrownError);
});
But that doesn't get triggered. There's clearly some error I am making in setting up the callbacks for errors - what could I try?
I think you don't see any
POST
because your data object doesn't contain only string values (I get aPOST
if I use{data: "content"}
).Following https://stackoverflow.com/a/19015673 and https://stackoverflow.com/a/18254775, you need to add some parameters (documentation):
I have managed to get the upload to work creating a FormData object and sticking my file into it. Here is the code:
This was inspired by the other StackExchange answers linked to by David Duponchel.