简体   繁体   中英

Streaming Chunk json data from POST request

I have a scenario that I need to upload an zip file.

In the zip file, there are lots of image files which will upload to AWS S3.

Because of the large amount of files in that zipfile, I want to get the information of upload process. In my opinion, the way I can get information is by using streaming response. Once server uploaded a file, respon a json to client.

Every time I upload a image to S3, I want to response a json object like the example bellow. example for json streaming response:

{
   "file_name": "imgae1.jpg",
   "s3_url": "http://s3.url/key/to/file",
   "other_key": "key for this uploaded file"
}

I'm trying to achieve this approach by using vue(cdn version) + axios(cdn version). The code bellow which is how I upload my zip file.

function upload() {
    var file = document.querySelector("#upload_file")
    if (file.files.length <= 0) return

    var formData = new FormData();
    formData.append("file", file.files[0]);
    formData.append("form_data", "form_data");

    axios({
        method: 'post',
        url: "http://127.0.0.1:8000/",
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        responseType: 'stream',
        data: formData
    }).then(function (response) {
        if (response.status >= 200 && response.status < 300) {
            alert("All images uploaded!")
        }
    })
}

but those examples I found are using axios npm package which I can't use.

Is there any recommend method or any resources that I can search? Thanks for helping!

You can try using fetch instead like this:

fetch("http://example.url", {
  method: "POST",
  body: formData,
  mode: "no-cors",
  header: {
    "Content-Type": "multipart/form-data",
  },
}).then((response) => {
  a = response.clone();
  a.json().then((data) => {
    //console.log('data', data)
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM