在我目前正在处理的应用程序中,有几个文件表单通过superagent提交给Express 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));
}
}
和this.state.image从文件输入设置如下:
updateImage: function(evt) {
this.setState({
image: evt.target.files[0]
}, function() {
console.log('image:', this.state.image);
});
},
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;
}
最后,文件接收端点如下所示:
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!');
});
};
目前,接收端点的on(‘file’)函数永远不会被调用,因此没有任何反应.以前,我尝试使用multer而不是Busboy的类似方法,但没有更多的成功(req.body包含解码的图像文件,req.files为空).
我在这里错过了什么吗?将文件从(ReactJS)Javascript应用程序上传到Express API端点的最佳方法是什么?
解决方法:
我认为superAgent正在设置错误的内容类型的application / x-form-www-encoded而不是multipart / form-data你可以通过使用attach方法解决这个问题,如下所示:
request.put(APIUtils.API_ROOT + 'upload/' + type + '/' + id)
.attach("image-file", this.state.image, this.state.image.name)
.end(function(res){
console.log(res);
});
有关attach方法的更多信息,请阅读此处的文档:http://visionmedia.github.io/superagent/#multipart-requests
因为这涉及到一个nodejs服务器脚本,所以我决定制作一个GitHub repo而不是一个小提琴:https://github.com/furqanZafar/reactjs-image-upload
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。