在我目前正在处理的应用程序中,有几个文件表单通过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端点的最佳方法是什么?
答案 0 :(得分:7)
我认为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);
});
有关attach方法的更多信息,请阅读此处的文档:http://visionmedia.github.io/superagent/#multipart-requests
因为这涉及到nodejs服务器脚本,所以我决定制作一个GitHub仓库而不是小提琴:https://github.com/furqanZafar/reactjs-image-upload
答案 1 :(得分:1)
根据经验,使用ajax上传文件时使用FormData
,但文件必须是唯一的表单字段/数据。如果您尝试将其与其他数据(例如用户名,密码或几乎任何内容)结合使用,则无效。 (可能有解决这个问题的工作,但我不知道)
如果您需要发送用户名/密码,则可以将其作为标题发送。
我采取的另一种方法是首先使用普通数据进行用户注册,然后在成功时我将FormData作为更新单独上传。
答案 2 :(得分:0)
反应文件上传iamges组件:
class ImageUpload extends React.Component {
constructor(props) {
super(props);
this.state = {file: '',imagePreviewUrl: ''};
}
_handleSubmit(e) {
e.preventDefault();
// this.uploadImage()
// TODO: do something with -> this.state.file
console.log('handle uploading-', this.state.file); }
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file) }
// XHR/Ajax file upload uploadImage(imageFile) {
return new Promise((resolve, reject) => {
let imageFormData = new FormData();
imageFormData.append('imageFile', imageFile);
var xhr = new XMLHttpRequest();
xhr.open('post', '/upload', true);
xhr.onload = function () {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.statusText);
}
};
xhr.send(imageFormData);
}); }
render() {
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
} else {
$imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
}
return (
<div className="previewComponent">
<form onSubmit={(e)=>this._handleSubmit(e)}>
<input className="fileInput" type="file" onChange={(e)=>this._handleImageChange(e)} />
<button className="submitButton" type="submit" onClick={(e)=>this._handleSubmit(e)}>Upload Image</button>
</form>
<div className="imgPreview">
{$imagePreview}
</div>
</div>
) } } React.render(<ImageUpload/>, document.getElementById("mainApp"));
服务器端图像保存和复制:
随着快递你需要npm安装'multiparty'。此示例使用multiparty来解析表单数据并提取图像文件信息。然后'fs'将临时上传的图像复制到更永久的位置。
let multiparty = require('multiparty');
let fs = require('fs');
function saveImage(req, res) {
let form = new multiparty.Form();
form.parse(req, (err, fields, files) => {
let {path: tempPath, originalFilename} = files.imageFile[0];
let newPath = "./images/" + originalFilename;
fs.readFile(tempPath, (err, data) => {
// make copy of image to new location
fs.writeFile(newPath, data, (err) => {
// delete temp image
fs.unlink(tempPath, () => {
res.send("File uploaded to: " + newPath);
});
});
});
})
}