使用 axios 发送文件,不使用 FormData api

sending a file with axios, without FormData api

我可以使用 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.

更多资源: