使用 axios 发送文件,没有 FormData api [英] sending a file with axios, without FormData api

查看:121
本文介绍了使用 axios 发送文件,没有 FormData api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 axios 和 FormData api 将文件发送到服务器,如下所示:

 persist(avatar){让数据 = new FormData();data.append('头像', 头像);axios.post(`/api/users/${this.user.name}/avatar`, 数据).then(() => flash('头像上传!'));}

传递给persist() 的avatar 参数是来自file"类型的表单输入的文件对象.

然后我可以在服务器端抓取文件.

是否可以不使用 FormData 来实现?也就是模拟FormData的工作?基本上,我试图了解 FormData api 完成的额外工作.也许使用 axios 是不可能的,我应该使用普通的 XMLHttpRequest 来做到这一点.

当然,简单地发送文件对象是行不通的:

axios.post(`/api/users/${this.user.name}/avatar`, {avatar: avatar})

在服务器端,头像对象将为空.我可以发送 avatar.name 之类的元数据,但不能发送整个对象.

解决方案

是的,可以在客户端手动进行编码.如果您真的想了解有关表单如何工作的每个小细节,您自己编写表单数据编码器可能会很有用.但是,对于大多数应用程序,我不推荐它.FormData API 应该在生产中使用.

您需要参考 RFC 7578 了解如何实现编码器.><块引用>

该规范定义了 multipart/form-data 媒体类型,它可以被各种应用程序使用,并被各种协议传输,作为用户填写的结果返回一组值的方式一个表格.

更多资源:

I can send a file to the server using axios and the FormData api, like that :

    persist(avatar){
        let data = new FormData();
        data.append('avatar', avatar);
        axios.post(`/api/users/${this.user.name}/avatar`, data)
            .then(() => flash('Avatar uploaded!'));
    }

The avatar param, passed to persist(), is a file object from a form input of type "file".

I can then grab the file on the server side.

Is it possible to do it without using FormData ? That is, to simulate the FormData work ? Basically, I'm trying to understand the extra work done by the FormData api. Maybe it's not possible using axios, and I should do that with plain XMLHttpRequest.

Of course, simply sending the file object won't work :

axios.post(`/api/users/${this.user.name}/avatar`, {avatar: avatar})

On the server side, the avatar object will be empty. I can send metadata like avatar.name, but not the whole object.

解决方案

Yes, it is possible to do the encoding manually on the client. Writing a form data encoder yourself may be useful if you really want to learn every little detail about how forms work. However, for most applications, I would not recommend it. The FormData API should be used in production.

You will need to refer to RFC 7578 for how to implement the encoder.

This specification defines the multipart/form-data media type, which can be used by a wide variety of applications and transported by a wide variety of protocols as a way of returning a set of values as the result of a user filling out a form.

More resources:

这篇关于使用 axios 发送文件,没有 FormData api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆