2

Trying to post the .png image files from a zip with jszip. The same code works when trying to do the same stuff with .xml files and .mod files, but not working with .png files.

The code that I'm using is:

JSZip.loadAsync(f) // f is the .zip file in the input field
.then(function(zip) {
    zip.forEach(function (relativePath, zipEntry) {
        zipEntry.async("string").then(function (data) {
            //data is the png image
            var pngfilepath="/serverImagesPath/" + zipEntry.name;
            var blob = dataURLtoBlob(data);
            $.ajax({
              type: "POST",
              url:  pngfilepath,
              data: blob,
              dataType: "binary",
            }).done(function ( ) {
                console.log('put correctly png- ' + pngfilepath);
            }).fail(function ( jqXHR, textStatus, errorThrown ) {
                console.log("err png: " + errorThrown, textStatus);
            });
        });
    });
});


function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

What I'm doing wrong?

Nau
  • 44
  • 4

1 Answers1

0

$.ajax will try to process the content as an unicode string. Add processData: false, see this answer (and the jQuery documentation):

$.ajax({
  type: "POST",
  url:  pngfilepath,
  data: blob,
  processData: false
})

You can also simplify a bit your code, .async() supports blob:

zipEntry.async("blob").then(function (blob) {
  // ...
  $.ajax({
    type: "POST",
    url:  pngfilepath,
    data: blob,
    contentType: "image/png", // or compute it
    processData: false
  })
  // ...
David Duponchel
  • 3,959
  • 3
  • 28
  • 36