【发布时间】:2015-01-18 16:02:38
【问题描述】:
在我目前正在处理的应用程序中,有几个文件表单通过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 端点的最佳方法是什么?
【问题讨论】:
-
你试过socket.io吗?可以用来传输二进制数据和jsons
-
@DmitryMatveev 我认为 socket.io 只是因为不幸地将一些 JSON/文件从客户端发送到服务器而有点矫枉过正。我真的不需要所有的实时功能
-
您使用的是什么前端。如果不是那么具体,你可以试试jQuery Form plugin。它发出必要的事件,如 beforeSubmit、uploadProgress、success、error。服务器端,可以使用Node Formidable。
标签: javascript node.js express reactjs