如何使用 Axios 作为 http 客户端将文件发送到 Node.js 服务器? [英] How to send files to a Node.js server using Axios as an http client?

查看:21
本文介绍了如何使用 Axios 作为 http 客户端将文件发送到 Node.js 服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Axios on the client side to send HTTP requests to a remote Node.js server. How might I go about sending files in the request body using Axios? I also have to send other information in the request body - sending just the files to the server will not suffice. How might I go about doing this? I am open to using a different HTTP client as well.

推荐答案

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

Use a FormData instance. On node you can use the form-data npm package. Then you just send that FormData instance as the data in an axios request.

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);

这篇关于如何使用 Axios 作为 http 客户端将文件发送到 Node.js 服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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