从 POST 请求流式传输 chunk json 数据
我有一个场景,我需要上传 zip 文件。
在 zip 文件中,有很多图像文件将上传到 AWS S3。
由于该zip文件中的文件量很大,我想获取上传过程的信息。在我看来,我获取信息的方式是使用流响应。服务器上传文件后,将 json 响应给客户端。
每次我将图像上传到 S3 时,我都想响应一个 json 对象,如下例所示。 json 流响应示例:
{
"file_name": "imgae1.jpg",
"s3_url": "http://s3.url/key/to/file",
"other_key": "key for this uploaded file"
}
我试图通过使用 vue(cdn 版本) + axios(cdn 版本) 来实现这种方法。 下面的代码是我上传 zip 文件的方法。
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!")
}
})
}
但我发现的这些示例使用的是我无法使用的 axios npm package 。
有什么推荐的方法或者可以搜索的资源吗? 感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用 fetch 代替,如下所示:
You can try using fetch instead like this: