0

When I tried to upload a file to my server, it works like a charm when I picked the file with an <input type="file" /> but it sends an empty (0 bytes) file when I use cordova-plugin-file. Guess what?

enguerran
  • 3,193
  • 3
  • 26
  • 42

1 Answers1

1

new File does not create the same object if you load cordova-plugin-file. Because window.File is overriden by cordova-plugin-file.

So I had to do a little trick (thanks to https://stackoverflow.com/a/29390393/178575):

const getFile = dirEntry =>
  new Promise((resolve, reject) => {
    dirEntry.file(file => {
      // window.File is modified by cordova, so we need this trick
      const reader = new FileReader()
      reader.onloadend = function() {
        const blob = new Blob([new Uint8Array(this.result)], {
          type: file.type
        })
        blob.name = file.name
        blob.lastModifiedDate = new Date(file.lastModifiedDate)
        resolve(blob)
      }
      reader.readAsArrayBuffer(file)
    })
})
enguerran
  • 3,193
  • 3
  • 26
  • 42
  • check this code on cozy-drive : https://github.com/cozy/cozy-drive/pull/873/files#diff-f112ba1b7dce001913124514eee437fb – enguerran Apr 17 '18 at 17:43