vue前后端分离上传图片

一、先在后端安装multiparty包

npm i multiparty

二、在后端项目中创建一个upload文件

三、在后端项目app.js中配置图片上传的路径

四、在routers文件下index.js中编写上传接口

//引入multiparty包
var multiparty = require('multiparty')
//上传图片
router.post('/uploadImg',(req,res)=>{
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req,(err,a,imgData)=>{
    res.send({
      code:200,
      path:'http://localhost:3000/' + imgData.file[0].path
    })
  })
})

五、前端图片展示列表

<el-table-column prop="path" label="图片">
        <template slot-scope="scope">
            <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.path" 
                :preview-src-list="[scope.row.path]">
            </el-image>
        </template>
</el-table-column>

六、前端form表单中点击按钮获取图片进行添加到数据库

<el-form-item label="图片" :label-width="formLabelWidth">
     <el-upload
             class="avatar-uploader"
             action="http://localhost:3000/uploadImg"
             :show-file-list="false"
             :on-success="success"
             :before-upload="beforeAvatarUpload">
          <img v-if="form.path" :src="form.path" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</el-form-item>
 methods: {
    success(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.path = res.path
      },
      beforeAvatarUpload(file) {
        const isGIF = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isGIF) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isGIF && isLt2M;
     }
}

七、最后样式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值