Jak*_*rsh 3 javascript node.js express reactjs
在我目前正在处理的应用程序中,有几个文件表单通过superagentExpress API端点提交.例如,图像数据的发布方式如下:
handleSubmit: function(evt) {
var imageData = new FormData();
if ( this.state.image ) {
imageData.append('image', this.state.image);
AwsAPI.uploadImage(imageData, 'user', user.id).then(function(uploadedImage) {
console.log('image uploaded:', uploadedImage);
}).catch(function(err) {
this.setState({ error: err });
}.bind(this));
}
}
Run Code Online (Sandbox Code Playgroud)
并this.state.image从文件输入设置如下:
updateImage: function(evt) {
this.setState({
image: evt.target.files[0]
}, function() {
console.log('image:', this.state.image);
});
},
Run Code Online (Sandbox Code Playgroud)
AWSAPI.uploadImage 看起来像这样:
uploadImage: function(imageData, type, id) {
var deferred = when.defer();
request.put(APIUtils.API_ROOT + 'upload/' + type + '/' + id)
.type('form')
.send(imageData)
.end(function(res) {
if ( !res.ok ) {
deferred.reject(res.text);
} else {
deferred.resolve(APIUtils.normalizeResponse(res));
}
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
而最后,文件接收端点看起来是这样的:
exports.upload = function(req, res) {
req.pipe(req.busboy);
req.busboy.on('file', function(fieldname, file) {
console.log('file:', fieldname, file);
res.status(200).send('Got a file!');
});
};
Run Code Online (Sandbox Code Playgroud)
目前,接收端点的on('file')功能永远不会被调用,因此没有任何反应.以前,我尝试过使用multer而不是Busboy的类似方法,但没有成功(req.body包含解码的图像文件,req.files是空的).
我在这里错过了什么吗?将文件从(ReactJS)Javascript应用程序上传到Express API端点的最佳方法是什么?
我认为superAgent设置了错误的内容类型application/x-form-www-encoded而不是multipart/form-data你可以通过使用附加方法来解决这个问题:
request.put(APIUtils.API_ROOT + 'upload/' + type + '/' + id)
.attach("image-file", this.state.image, this.state.image.name)
.end(function(res){
console.log(res);
});
Run Code Online (Sandbox Code Playgroud)
有关attach方法的更多信息,请阅读此处的文档:http://visionmedia.github.io/superagent/#multipart-requests
因为这涉及到一个nodejs服务器脚本,所以我决定制作一个GitHub repo而不是一个小提琴:https://github.com/furqanZafar/reactjs-image-upload
| 归档时间: |
|
| 查看次数: |
6558 次 |
| 最近记录: |