react+express实现图片上传和显示
express后端部分
首先使用的是express框架,提交文件使用的是Multer插件。
https://www.npmjs.com/package/multer
//首先在router中引入multer文件
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
// 解决中文名乱码的问题
file.originalname = Buffer.from(file.originalname, "latin1").toString(
"utf8"
);
cb(null, file.originalname)
}
})
//需要在路由中添加中间件upload.single("img"),中间件当中的img则是input中name所命名的值。
router.post('/life', upload.single("img"), life_handleLife.createLife)
//这是路由操作模块multer会在req中添加一个req.file文件当中包含了图片的所有信息。
exports.createLife = (req, res) => {
console.log(req.body, req.file);
const lifeInfo = req.body
const imagename = req.file.originalname
const sql = 'insert into life set ?'
db.query(sql, { title: lifeInfo.title, content: lifeInfo.content, image: imagename, status: 0, life_delete: 0 }, (err, result) => {
if (err) {
res.cc(err)
}
if (result.affectedRows !== 1) {
res.cc('创建失败')
}
res.cc('创建成功', 0)
})
}
前端react中添加图片的操作
//用于选择文件
<input type="file" ref={fileRef} />
//fileRef.current.files[0]里面包含了图片的所有信息。
//需要将需要传入的文件定义成formdata格式
const formsdata = new FormData()
formsdata.append("title", titleRef.current.input.value)
formsdata.append("content", contentRef.current.value)
formsdata.append("img", fileRef.current.files[0])
console.log(formsdata)
//请求头也需要设置对应的格式'Content-Type': 'multipart/form-data'
headers: {
Authorization: localStorage.getItem('token'),
'Content-Type': 'multipart/form-data'
},
//下面是完整的提交代码
const handleLifetitle = () => {
// console.log(fileRef.current.files[0])
const formsdata = new FormData()
formsdata.append("title", titleRef.current.input.value)
formsdata.append("content", contentRef.current.value)
formsdata.append("img", fileRef.current.files[0])
console.log(formsdata)
if (titleRef.current.input === '' || contentRef.current.value === '') {
return message.error('标题和内容不能为空')
} else {
// const life = { title: titleRef.current.input.value, content: contentRef.current.value, img: fileRef.current.files[0] }
axios({
url: '/life',
method: 'POST',
headers: {
Authorization: localStorage.getItem('token'),
'Content-Type': 'multipart/form-data'
},
data: formsdata
// data: qs.stringify(formsdata)
}).then(res => {
console.log(res.data)
if (res.data.status === 0) {
message.success(res.data.message)
}
if (res.data.status === 1) {
message.error(res.data.message)
}
})
}
}