我可以使用 axios 和 FormData api 将文件发送到服务器,如下所示:
persist(avatar){
let data = new FormData();
data.append('avatar', avatar);
axios.post(`/api/users/${this.user.name}/avatar`, data)
.then(() => flash('Avatar uploaded!'));
}
传递给 persist() 的头像参数是来自“file”类型的表单输入的文件对象。
然后我可以在服务器端获取文件。
不使用 FormData 是否可以做到这一点?也就是模拟FormData的工作?基本上,我试图理解 FormData api 完成的额外工作。也许使用 axios 是不可能的,我应该使用纯 XMLHttpRequest 来做到这一点。
当然,仅仅发送文件对象是行不通的:
axios.post(`/api/users/${this.user.name}/avatar`, {avatar: avatar})
在服务器端,头像对象将为空。我可以发送元数据,例如 avatar.name,但不能发送整个对象。
最佳答案
是的,可以在客户端手动进行编码。如果您确实想了解有关表单工作原理的每一个小细节,那么自己编写表单数据编码器可能会很有用。但是,对于大多数应用程序,我不推荐它。 FormData
API 应该在生产中使用。
您需要引用RFC 7578了解如何实现编码器。
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.
更多资源:
关于javascript - 使用 axios 发送文件,不使用 FormData api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51559445/