如何使用Axios作为http客户端将文件发送到Node.js服务器?

时间:2017-03-28 18:39:48

标签: node.js http axios

我在客户端使用Axios将HTTP请求发送到远程Node.js服务器。我如何使用Axios在请求体中发送文件?我还必须在请求正文中发送其他信息 - 仅将文件发送到服务器是不够的。我该怎么做呢?我也愿意使用不同的HTTP客户端。

1 个答案:

答案 0 :(得分:1)

使用FormData个实例。在节点上,您可以使用form-data npm包。然后,您只需将FormData实例作为data发送到axios请求中。

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

axios.post("http://foo.com/submitform.php", formData);
相关问题