我试图将图像(ReactJs)上传到我的服务器(NodeJs+ Express+ multerJs)到数字海洋。
我使用带有 multipart/form-data 的 POST 请求;
我从 multerJs 收到一条成功的消息,但我可以在服务器上的日志中看到 files: [] 有一个空数组。而那个Digital Ocean当然没有添加任何文件。
当我对表单执行相同的 Post 请求而不处理表单的提交时,一切正常并且 Files 数组不为空。上面的代码正在运行:
<form method="post" enctype="multipart/form-data" action="http://localhost:3004/upload_image_test_4" > </form>
客户端 React.js :
export default class Select_size extends React.Component {
on_form_submit = (e) => {
e.preventDefault();
const fileInput = this.state.file;
const formData = new FormData();
formData.append('file', fileInput);
const options = {
method: 'POST',
body: formData,
headers: {
'Access-Control-Allow-Origin': '*',
Accept: 'application/json',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
}
};
var url =
this.state.action_link +
'?url=' +
this.state.id_user +
'/' +
this.state.id_draft +
'&name=' +
this.state.name_file;
fetch(url, options);
};
onChange = (e) => {
this.setState({ file: e.target.files[0] });
};
constructor(props) {
super(props);
this.state = {
files: [],
};
this.onChange = this.onChange.bind(this);
}
render() {
return (
<form onSubmit={this.on_form_submit} enctype="multipart/form-data">
<input type="file" name="myImage" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)}
}
服务器端(Node.js/ExpressJs/Multer/Digital Ocean):
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const aws = require('aws-sdk');
const spacesEndpoint = new aws.Endpoint('fra1.digitaloceanspaces.com');
const s3 = new aws.S3({
endpoint: spacesEndpoint,
accessKeyId: 'myID',
secretAccessKey: 'MySecretKey'
});
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'bucketName',
acl: 'public-read',
key: function(request, file, cb) {
cb(null, urlBucket + name_image);
}
})
}).array('upload', 1);
router.post('/upload_image_test_4', function(request, response, next) {
upload(request, response, function(error) {
console.log(request, 'the request');
if (error) {
console.log(error);
return response.json(error, 'error');
}
console.log('File uploaded successfully.');
return response.json('success its uploaded to digital ocean');
});
});
module.exports = router;
如果有人可以帮助我!(我已经疯狂地用谷歌搜索了,,,)谢谢!