【问题标题】:Upload a string as file将字符串上传为文件
【发布时间】:2017-06-14 16:20:04
【问题描述】:
如何将字符串作为文件上传,并使用node.js 进行 http 发布请求?
这是我尝试过的:
var unirest = require('unirest');
unirest.post('127.0.0.1/upload')
.headers({'Content-Type': 'multipart/form-data'})
.attach('file', 'test.txt', 'some text in file') // Attachment
.end(function (response) {
console.log(response.body);
});
但是什么都没发生
【问题讨论】:
标签:
node.js
http
file-upload
upload
unirest
【解决方案1】:
您必须从本地文件系统中指定一个文件。所以我建议
-
你create the file locally
var fs = require('fs');
fs.writeFile("/tmp/test", "some text in file", function(err) {
if(err) { return console.log(err); }
console.log("The file was saved!");
});
-
发送文件
var unirest = require('unirest');
unirest.post('127.0.0.1/upload')
.headers({'Content-Type': 'multipart/form-data'})
.attach('file', '/tmp/test')
.end(function (response) {
console.log(response.body);
});