Element 以二进制的形式 自定义上传图片

一,只有在上传文件之前的钩子函数中才可以获得最初的文件(文件本身的二进制形式),用以以上传服务器。
还需要使用formdata来承载数据,便于接收
<template>
  <div>
    <el-upload
      action="http://localhost:3000/picture"
      :http-request = "upload"
      :before-upload = "beforeUp"
      :headers="headers"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-progress="progress"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    
    <el-row>
      <el-button type="info" plain @click="getimages">信息按钮</el-button>
    </el-row>
 </div>
</template>
<script>
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        headers:{},
        imgArr:[]
      };
    },
    methods: {
      beforeUp(file){
        console.log(file);
        var formData = new FormData();
        formData.append('file',file);
        this.$http.post('/picture',formData)
      },
      handleRemove(file, fileList) {
        /* 移除 */
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        /* 预览 */
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
        console.log(file);
        this.$http.post('/picture',file)
      },
      progress(){
        console.log('上传中');
      },
      upload(res){
        // this.imgArr.push(res)
        // console.log(res);
        // this.$http.post('/picture',res)
      },
      getimages(){
        // console.log(this.imgArr);
        // this.$http.post('/picture',this.imgArr)
      }
    },
    created(){
      // this.$http.get('/picture')
      // this.headers ={Authorization : 'Bearer '+(localStorage.token || '')}
    }
 
  }
</script>
二,node.js服务器使用multer插件 接收上传的图片  ,multer插件需要接收二进制的文件
 
var multer = require('multer')
const upload = multer({ dest: 'uploads/' });
router.use(upload.single('file')); 

router.post('/',upload.single('file'),async(req,res)=>{   //此刻图片已存入服务器
  console.log(req.body);
  console.log(req.file);
})
 
如果有类似问题bug,可以留言一起研究,共同进步,哈哈 。。
原文地址:https://www.cnblogs.com/500m/p/11908905.html