vue + multer 上传图片

vuejs(element-ui) + express (multer)上传文件

  1.npm install multer --save

  2. 新建vue文件

    主要代码:

         <form method="POST" enctype="multipart/form-data" class="form-horizontal" @submit.prevent="submit" ref="inputUpload">
            <input type="file" name="resourceName" accept="audio/mpeg,image/png,image/jpeg" style="display:inline-block;250px;"
              v-on:change="getFileInfo" />
            <div slot="tip" class="el-upload_tip">Only .mp3, .png and .jpg file can be uploaded and size limit is 10MB.</div>
            <el-button native-type="submit" class="el-icon-upload" :disabled="!formatFile">upload</el-button>
          </form>
    
getFileInfo: function (event) {
        if (event.target.files && event.target.files.length) {
          this.upFile = event.target.files[0];
//主要读取file 显示一些信息
//....
submit: function (event) {
        var self = this;
        var fd = new FormData(event.target);
        fetch('/uploadResource', {
          method: 'POST',
          body: fd,
          credentials: "include"
        }).then(response => {//....})
          } 
3.  fetch里面的url (读取文件存放到指定的目录下面)
 
var fs = require('fs')
var multer = require('multer')
var path = "./public/static/upload";

// if (!fs.existsSync(path)) {
//     fs.mkdirSync(path)
// }

var storage = multer.diskStorage({
    destination: function (req, res, cb) {
        cb(null, path);
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

var upload = multer({
    storage: storage,
    limits: {
        fieldNameSize: '10M'
    }
})


exports.singleUpload = function (req, res) {
    s = uploadResource.single('imgUpload');
    s(req, res, function (err) {
        if (err) {
            res.send({
                'status': 'failed'
            })
        } else {
            res.send({
                'status': 'ok'
            })
        }
    })
}
 
4. api增加到router
router.post('/getFile',upload.singleUpload)
 
其他补充:如果是excel 换成
    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
 
    api里面解析的时候 用到 var xlsx = require('xlsx');//自己了解
 
 
 
 
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/cylblogs/p/6758118.html