Async/Await in `onBeforeFileAdded() throw 'Cannot read property 'size' of undefined'

Started by mowolf1 reply1,089 views
mowolfOriginal post
#1

Hi,

I am struggling with asynchronous calls in onBeforeFileAdded(). I want to only upload images with a certain image resolution of 12MPX. My implementation rejects files lower than 12mpx successfully. However all other files throw this error:

[Uppy] [12:55:55] Error: Multiple errors occurred while adding files:

 * Cannot read property 'size' of undefined
    at Uppy.addFiles (index.js?b880:866)
    at Dashboard._this.addFiles (index.js?ef92:391)
    at Object.Dashboard._this.handleInputChange (index.js?ef92:513)
    at Object.AddFiles._this.onFileInputChange [as change] (AddFiles.js?abc5:28)
    at HTMLInputElement.eventProxy (preact.esm.js?30bf:308)

Here is a minimal code which produces this behavior.

return new Uppy({
        onBeforeFileAdded: async (currentFile, files) => {
          // Check mpx
          const mpx = await this.getMPX(URL.createObjectURL(currentFile.data))
          if (mpx < 12) {
            return false
          }
          return true
        },
      })

The function calculating the megapixels for a given imageUrl:

getMPX(imgUrl) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = () => {
          resolve((img.width * img.height) / 1000000)
        }
        img.onerror = reject
        img.src = imgUrl
      })
    },

If you remove the await and async and replace the function with a number (e.g. Math.random()*24) it works (i.e. about 50% of the images are getting uploaded).

I am struggling to find what I am doing wrong. Is an async onBeforeFileAdded() not working in general? I do have various things to check server side before the file should be uploaded (e.g. duplicate) and wanted to call the api’s in onBeforeFileAdded() as well.

Any help would be great!

mowolf
#2

I figured it out to make Uppy work with an async call. You need to create a plugin and hook onto the this.uppy.addPreProcessor function.

However now I am struggling to display an UI with Vue. Using

    const target = this.opts.target
if (target) {
  this.mount(target, this)
}

results in

Error: Invalid target option given to UploadRestrictions.If you meant to target an HTML element, please make sure that the element exists. Check that the <script> tag initializing Uppy is right before the closing </body> tag at the end of the page.

I also wrote a cue component but this gets me the error in the render hook:

TypeError: h is not a function
    at RestrictionsPlugin.render

There is basically zero documentation on that. I tried to copy as much code as possible from the @uppy/vue components and the @uppy/plugins but have no idea how to adjust this to vue.