elementUI自定义上传文件 前端后端超详细过程
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                在使用Element UI的Upload组件进行文件上传时,可以通过定制before-upload钩子函数来实现前端和后端的超详细过程。以下是一个简化的例子:
前端(Vue.js):
<template>
  <el-upload
    :action="uploadUrl"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :on-error="handleError">
    <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
  </el-upload>
</template>
 
<script>
export default {
  data() {
    return {
      uploadUrl: 'http://your-backend-endpoint/upload'
    };
  },
  methods: {
    beforeUpload(file) {
      // 在这里可以进行文件的验证,例如文件格式、大小等
      // 如果验证失败,返回 false 会阻止上传
      // 如果需要自定义上传动作(例如添加headers或者其他参数),可以在这里发起请求
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传的文件大小不能超过 2MB!');
        return false;
      }
      
      // 这里可以返回一个Promise,根据Promise的结果决定是否继续上传
      return new Promise((resolve, reject) => {
        // 在这里进行你需要的任何操作,例如发送请求到后端验证文件信息
        // 验证通过后调用 resolve() 继续上传,调用 reject() 中断上传
        resolve();
      });
    },
    handleSuccess(response, file, fileList) {
      // 文件上传成功的处理逻辑
      console.log('File uploaded successfully:', response);
    },
    handleError(err, file, fileList) {
      // 文件上传失败的处理逻辑
      console.error('Error uploading file:', err);
    }
  }
};
</script>后端(Node.js):
const express = require('express');
const multer = require('multer');
const app = express();
 
// 设置 multer 的存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/') // 确保这个目录已经存在
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
const upload = multer({ storage: storage })
 
// 定义上传接口
app.post('/upload', upload.single('file'), (req, res) => {
  // 这里可以添加对文件的验证逻辑,例如检查文件类型、大小等
  // 验证通过后,可以处理文件上传至服务器的逻辑
  // 处理完毕后,返回响应
  res.json({ message: 'File uploaded successfully' });
});
 
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});在这个例子中,前端使用Element UI的<el-upload>组件,并通过:before-upload属性绑定了一个方法beforeUpload。这个方法会在文件选择后立即被调用,并且如果返回false,则会阻止文件的上传。如果返回一个Promise,则会等待Promise的状态变化来决定是否继续上传。后端使用Express.js框架和multer中间件处理文件上传的接口
评论已关闭