admin管理员组文章数量:1387294
I want to upload a file to a restful api service from my javascript application. It should use a local path like "c:/folder/test.png" and upload to something like "localhost/uploads", is there a easy approch, I am a little lost ing to the upload part and have tryed searching around, but didn't find any that matched my case, and I have tryed this code below:
var request = require('request');
var url = "http://localhost/uploads";
var req = request.post(url, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', fs.createReadStream("C:/kristian/Devbeasts-small.png"));
this code gives me the error: Error: Cannot find module 'request'
It requires a multipart form-data.
I want to upload a file to a restful api service from my javascript application. It should use a local path like "c:/folder/test.png" and upload to something like "localhost/uploads", is there a easy approch, I am a little lost ing to the upload part and have tryed searching around, but didn't find any that matched my case, and I have tryed this code below:
var request = require('request');
var url = "http://localhost/uploads";
var req = request.post(url, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', fs.createReadStream("C:/kristian/Devbeasts-small.png"));
this code gives me the error: Error: Cannot find module 'request'
It requires a multipart form-data.
Share Improve this question edited Oct 19, 2016 at 12:41 Kristian Tang asked Oct 19, 2016 at 12:11 Kristian TangKristian Tang 451 gold badge1 silver badge8 bronze badges1 Answer
Reset to default 2The post
method can take an object containing an url
and a formData
object as first parameter, as seen here.
var formData = {
name: 'file1',
file: {
value: fs.createReadStream('C:/kristian/Devbeasts-small.png'),
options: {
filename: 'Logo_flame.png',
contentType: 'image/png'
}
}
};
request.post({url:'http://localhost/uploads', formData: formData},
function cb(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
}
);
本文标签: javascriptnodejs multipartformdata local file upload to apiStack Overflow
版权声明:本文标题:javascript - node.js multipartform-data local file upload to api - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744562712a2612861.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论