fxmontigny / quill-image-upload

A module for Quill rich text editor to upload images to be selected from toolbar editor.
107 stars 43 forks source link

Enhancement: Ability to use custom uploader #9

Closed jaskiratr closed 5 years ago

jaskiratr commented 5 years ago

It would be helpful to be able to modify sendToServer(file) in order to handle file upload manually. I'm trying to upload the file to Firebase Storage, which does not use POST request. Documentation

What would be the best way to expose sendToServer() as an option to handle the upload logic?

I've modified the function as below:

sendToServer(file) {
    // Handle custom upload
    if (this.options.customUploader) {
      this.options.customUploader(file, dataUrl => {
        this.insert(dataUrl)
      })
    } else {
      const url = this.options.url || 'your-url.com',
        method = this.options.method || 'POST',
        headers = this.options.headers || {},
        callbackOK =
          this.options.callbackOK || this.uploadImageCallbackOK.bind(this),
        callbackKO =
          this.options.callbackKO || this.uploadImageCallbackKO.bind(this),
        fd = new FormData()
      fd.append('image', file)

      const xhr = new XMLHttpRequest()
      // init http query
      xhr.open(method, url, true)
      // add custom headers
      for (var index in headers) {
        xhr.setRequestHeader(index, headers[index])
      }

      // listen callback
      xhr.onload = () => {
        if (xhr.status === 200) {
          callbackOK(JSON.parse(xhr.responseText), this.insert.bind(this))
        } else {
          callbackKO({
            code: xhr.status,
            type: xhr.statusText,
            body: xhr.responseText
          })
        }
      }

      xhr.send(fd)
    }
  }

Let me know if you find this useful for general use. Happy to work on a pull request. Many thanks for providing the plugin!

fxmontigny commented 5 years ago

Hi,

This is a great idea. I will integrate now.

fxmontigny commented 5 years ago

Your proposal are now integrate into the version 0.1.3.

Thx very much @jaskiratr .

jaskiratr commented 5 years ago

Thank you so much @fxmontigny !