我正在尝试使用multer
包保存图像文件。
这是我们的registration.js
,其中包含注册表。以下脚本没有错误,但是我们不知道如何访问url中的文件或向用户显示图像(确切地讲如何以MIME格式保存文件)。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Registration extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var config = {
headers: {
'Content-Type': 'multipart/form-data'
}
};
var formData = new FormData();
var imagefile = document.getElementById('profilePicture');
formData.append('name',document.getElementById('name').value);
formData.append('email',document.getElementById('email').value);
formData.append('telegramId',document.getElementById('telegramId').value);
formData.append('password',document.getElementById('password').value);
formData.append('image', imagefile.files[0]);
console.log(formData);
axios.post('/registration', formData,config).then(function(res){
console.log(res.data+'res');
}).catch(console.error);
}
render() {
return (<form className="registrationForm">
<input type="text" name="name" id="name" required="required" placeholder="name" />
<br/>
<input type="email" id="email" required="required" placeholder="email"/>
<br/>
<input type="text" id="telegramId" required="required" placeholder="telegramID"/>
<br/>
<input type="password" id="password" required="required" placeholder="password"/>
<br/>
<input type="file" id="profilePicture"/>
<br/>
<button className="registerButton" onClick={this.handleSubmit}>Register</button>
</form>)
};
}
这是服务器端代码:
var multer = require('multer')
var upload = multer({ dest: '../assets/uploads/' })
app.post('/registration',upload.single('image'), (req, res) => {
// console.log(req.body);
console.log(req.file);
});
这就是控制台记录的内容!
{ fieldname: 'image',
originalname: 'sharif-logo-png-transparent.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'uploads/',
filename: 'e098a8370f444f321acd9aae668538fd',
path: 'uploads\\e098a8370f444f321acd9aae668538fd',
size: 271654
}
答案 0 :(得分:2)
multer
已经负责将文件保存到磁盘,因此您要做的就是使该文件夹可访问,以供<img>
标记(或任何您想用来显示的文件夹)使用他们)。一个好的解决方案是express.static
:
const { static } = require('express');
app.use('/images/', static('../assets/uploads/'));
然后您可以在客户端代码中使用它们:
<img src="/images/e098a8370f444f321acd9aae668538fd"></img>
您完全不必在.post('/registration')
处理程序中处理文件。