Express+vue+element-ui上传图片带参数给后台formData格式

Express+vue+element-ui上传图片时遇到的问题:最重要的问题
node+express用multer上传图片
当后台接口 upload.single(‘file’) 写的是file时。
在这里插入图片描述
我们可以直接在action 中写入 接口连接
在这里插入图片描述
当后台接口 upload.single(‘file’) 写的不是file时。
如:此时在action 中写时 无法上传图片。
在这里插入图片描述
这时需要我们使用 http-request (覆盖默认的上传行为,可以自定义上传的实现)。
带参数给后台formData格式数据,实现上传。
在这里插入图片描述
在这里插入图片描述
切记 传过去FormData 中的名字要和后台Express中的一样如下:
在这里插入图片描述在这里插入图片描述
Express 接口代码

//图片上传  用日期命名图片存储的文件夹
//获取时间

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
    return currentdate.toString();
}

var datatime = 'public/images/' + getNowFormatDate();
//将图片放到服务器
var storage = multer.diskStorage(
	//destination  完整形态
    // destination: function (req, file, cb) {
    //     cb(null, '/tmp/my-uploads')
    // },
    // destination 是一个函数,负责创建文件夹
    destination: datatime,
    //filename 给上传文件重命名
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
var upload = multer({
    storage: storage
});
router.post('/uploads', upload.single('file'), function (req, res, next) {
    res.send("上传成功")
});

vue + element ui 上传图片代码

<template>
  <div>
    {{msg}}
    <!--上传-->
    <!--margin: 0 auto-->
    <!--accept	接受上传的文件类型-->
    <!--http-request 覆盖默认的上传行为,可以自定义上传的实现-->
    <div style="width:300px;height:300px">
      <el-upload
        class="upload-demo"
        action=""
        :http-request="upload"
        :on-success="Tusuccess"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
        :with-credentials="true"
        :file-list="fileList"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
      </el-upload>
    </div>
    <!--弹框-->
    <el-dialog
      title="提示"
      :visible.sync="imgDialogVisible"
      width="30%">
      <img style="width: 100%" :src="dialogImageUrl" alt="">
      <span slot="footer" class="dialog-footer">
    <el-button @click="imgDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="imgDialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "",
    data: function () {
      return {
        imgDialogVisible: false,
        msg: 'This is a Vue project daohang2 --图片上传',
        fileList: [{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }, {
          name: 'food2.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }],
        dialogImageUrl: '',
      }
    },
    create: function () {
    }, /*渲染前调用*/
    mounted: function () {
    }, /*渲染后调用*/
    methods: {
      handleRemove(file, fileList) {
        this.$message.success('删除成功');
      },
      handlePreview(file) {
        console.log(file);
        this.dialogImageUrl = file.url;
        this.imgDialogVisible = true;
      },
      Tusuccess(response, file, fileList) {
        console.log(response)
        console.log(file)
        console.log(fileList)
      },
      beforeAvatarUpload(file) {
        //const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        /*if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }*/
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        /*return isJPG && isLt2M;*/
        return isLt2M;//如果只限制大小只返回isLt2M即可,必须返回,不然不生效
      },
      upload(file) {
        console.log(file);
        let fd = new FormData();
        fd.append('file', file.file)
        var self = this;
        this.axios.post("/localhost/uploads",fd)
          .then(function (response) {
            self.$message.success('上传成功');
          })
          .catch(function (error) {
            self.$message.error('上传失败');
          })
      }
    }  /*方法*/
  }
</script>

<style scoped>

</style>

github:
vue:
https://github.com/Usered/demo/blob/master/Vue/FirstVue/src/main/daohang2.vue
Express
https://github.com/Usered/demo/blob/master/Express/mydemo/routes/index.js

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值