react+express实现图片上传和回显

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)
                }
            })
        }
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值