3

Nuxt3 documentation suggests using its built-in $fetch method for making API calls. I'm trying to show the upload progress for a file uploader. I've done it with Axios before, but it does not work with the $fetch method. Here is my code which works with Axios:

//...
const config = {
  onUploadProgress: (progressEvent) => {
    progress.value = Math.round((progressEvent.loaded / progressEvent.total)*100);
  }
}

$fetch('/portfolio/upload/', {method: 'POST', body: formdata, config});
//...

I've looked into the ohmyfetch documentation on GitHub, but I did not find anything. Any idea about how can I handle upload progress using the $fetch method?

mo3n
  • 1,522
  • 2
  • 10
  • 34
  • I'm not even sure this can be done with Axios. For me, it was a fetch thing. Maybe create an issue on the repo. – kissu Sep 22 '22 at 09:04
  • 1
    @kissu there is already an open issue there https://github.com/unjs/ohmyfetch/issues/45 – mo3n Sep 22 '22 at 09:13

1 Answers1

3

Fetch or ofetch don't support uploading progress, right now this can be done only in browser with XMLHttpRequest, something like this:

function upload (url, file) {
    const form = new FormData()
    form.append('file', file)

    const xhr = new XMLHttpRequest()
    xhr.open('post', url, true)
    xhr.upload.onprogress = function (ev) {
        // Upload progress here
        console.log(ev)
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            // Uploaded
            console.log('Uploaded')
        }
    }
    xhr.send(form)
}

You can find more about this here Upload progress indicators for fetch?

Vedmant
  • 2,265
  • 1
  • 27
  • 36
  • Pretty sure `XMLHttpRequest` is not needed and at least `fetch` support it. – kissu Feb 25 '23 at 17:40
  • 1
    @kissu No, it doesn't, https://fetch.spec.whatwg.org/#fetch-api : `The fetch() method is relatively low-level API for fetching resources. It covers slightly more ground than XMLHttpRequest, although it is currently lacking when it comes to request progression (not response progression).` – Vedmant Feb 26 '23 at 22:35
  • What's the difference between [download progression](https://javascript.info/fetch-progress) and request progression? – kissu Feb 27 '23 at 00:49
  • @kissu request progression is the same as upload progression, when you upload large files. Even in the link you added there is text: `Please note: there’s currently no way for fetch to track upload progress. For that purpose, please use XMLHttpRequest, we’ll cover it later.` – Vedmant Feb 27 '23 at 15:39
  • @kissu it's download progress vs upload progress – select Mar 06 '23 at 10:18