vue实现文件上传,前后端

前端封装el-upload组件,父组件传值dialogVisible(用于显示el-dialog),子组件接收,并且关闭的时候返回一个值(用于隐藏el-dialog),最多上传五个文件,文件格式为.jpg\pdf\png

<template>
    <div>
       <el-dialog  width="30%"  :visible.sync="dialogShow" append-to-body @close='handleCancle' title="上传发票" class="uploadDialog">
        <!-- 
            list-type="picture"
           :file-list="fileList"
            :on-change="changeFileLength"
            :on-success="handleAvatarSuccess"
            multiple
        -->
        <el-upload
           ref="upload"
           :auto-upload="false"
           :on-remove="handleRemove"
           :on-change="changeFileLength"
           :limit="5"
           :on-exceed="handleExceed"
           action="https://jsonplaceholder.typicode.com/posts/"
           list-type="picture"
           :file-list="fileList"
           accept=".pdf,.jpg,.png" 
           multiple
           >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">选择文件</div>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf文件,且不超过500kb</div> -->
        </el-upload>
        <el-button @click="upload" type="success">上传文件</el-button>
      </el-dialog> 
    </div>
</template>
<script>
import {  upload1 } from "@/api/invoice/invoiceManagement";
import pdfde from "./pdfdefine.png";

export default {
    name: "uploadCT",
    props:{
        dialogVisible:{
            type:Boolean,
            default:false,
            require:true,
        }
    },
    watch: {
        dialogVisible: {
            handler(val) {
                this.dialogShow = val
            },
            deep: true, // 深度监听
            immediate: true, // 初次监听即执行  
        },
    },

    data(){
        return{
            // 上传文件的列表
            uploadFiles: [],
            // 上传文件的个数
            filesLength: 0,
            // 上传需要附带的信息
            info:{
                id:"",
                name:"",
            },
            //显示
            dialogShow:this.dialogVisible,
            //缩略图
            fileList:[],
            def : pdfde,
        }
    },

    methods:{
        //删除
        handleRemove(file, fileList){
            console.log("移除");
            this.fileList=this.fileList.filter(item=>item.name!=file.name);
            this.uploadFiles =this.uploadFiles.filter(item=>item.name!=file.name);
            this.filesLength=fileList.length;
        },
        //超出限制提示
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 5 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
        },
        //关闭
        handleCancle(){
            this.uploadFiles= [];
            // 上传文件的个数
            this.filesLength= 0;
            this.dialogShow = false;
            this.$emit('closeUploadDialog',this.dialogShow);
            this.$refs.upload.clearFiles();
            this.fileList=[];
        },
        // 选择文件触发事件
        changeFileLength(file, fileList){
            console.log("选择",file,fileList);
            this.filesLength = fileList.length;
            if(file.name.endsWith('.pdf')){
                this.fileList.push({
                    name:file.name,
                    url: this.def,
                })
            }else{
                this.fileList.push({
                    name:file.name,
                    url:file.url,
                })
            }
            this.uploadFiles=fileList;
        },

        // 用户点击上传调用
        async upload(){
            // 触发上传 调用配置 :http-request="uploadFile"
            // 即触发 uploadFile函数
            console.log('点击',this.filesLength);
            if(this.filesLength>0){
                this.fileList[0].staus='ready';
                // await this.$refs.upload.submit();
                await this.uploadFilesToService();
                // 上传完成后执行的操作 ...
                
            }else{
                this.$modal.msgError( "请先选择文件");
            }
        },
        //上传按钮
        async uploadFilesToService(){
            console.log("上传",this.uploadFiles.length,this.filesLength);
            let that = this;
            if (this.uploadFiles.length == this.filesLength){
                // 创建FormData上传
                let fd = new FormData()
                // 将全部文件添加至FormData中qingxian
                this.uploadFiles.forEach(file => {
                    fd.append('file', file.raw)
                })
                // 将附加信息添加至FormData
                fd.append("id", this.info.id)
                fd.append("name", this.info.name)
                // 配置请求头
                const config = {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    }
                }
                console.log("参数",fd);
                // 上传文件
                await upload1(fd).then(res => {
                    /*上传成功处理*/
                    console.log(res);
                    if(res.msg=='上传成功'){
                        this.uploadFiles=[];
                        this.filesLength = 0;
                        this.dialogShow = false;
                        this.$emit('closeUploadDialog',this.dialogShow);
                        this.$refs.upload.clearFiles();
                        this.uploadFiles = [];
                        this.filesLength = 0;
                        this.fileList = [];
                        this.$refs.upload.clearFiles();
                        this.$modal.msgSuccess("上传成功");
                    }else{
                        console.log("失败");
                        const arr1 =res.data.data;
                        this.$nextTick(()=>{
                            arr1.map(item1=>{
                                this.uploadFiles = this.uploadFiles.filter(item2=>item2.name!=item1);
                                this.fileList = this.fileList.filter(item=>item.name!=item1);
                            })
                        })
                        
                        this.filesLength=this.filesLength-arr1.length;
                        console.log(this.uploadFiles,this.filesLength);
                        this.$modal.msgError(res.data.msg);
                    }
                    
                }).catch(err => {/*报错处理*/console.log("报错",err);});

            }
        }
    }
}
</script>


    
    

后端接收

@PostMapping("/upload")
    public AjaxResult upload(@RequestParam(value = "file") MultipartFile[] file)
    {
        ArrayList<String> successList = new ArrayList<>();
        try {
            String localPath = "";
            //1.1获取当前日期,当做本地磁盘的目录
            Date nowDate = DateUtils.getNowDate();
            String format = new SimpleDateFormat("YYYYMMDD").format(nowDate);
            String localPathPrefix = "C:\\"+format;
            for(MultipartFile f:file){
                // 获取文件名
                String fileName = f.getOriginalFilename();
                // 获取文件后缀
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                // 保存文件到本地磁盘
                localPath = localPathPrefix+"\\"+fileName;
                File localFile = new File(localPath);
                if (!localFile.getParentFile().exists()) {
                    localFile.getParentFile().mkdirs();
                }
                //写入到本地磁盘
                f.transferTo(localFile);
                // 获取文件在本地磁盘上的路径
                String filePath = localFile.getAbsolutePath();
                log.info("文件名称:"+fileName+"已经存入本地磁盘,全路径为:"+filePath);
                //成功一个,将文件名放入一个successList
                int i = finInvoiceDefineService.OCRToService(filePath);
                //删除本地临时磁盘文件
                if (localFile.delete()) {
                    log.info(localFile.getName() + "已经删除");
                } else {
                    log.info("文件删除失败");
                }
            }
            //删除本次磁盘的日期目录
            File file1 = new File(localPathPrefix);
            if (file1.delete()) {
                log.info(file1.getName() + "已经删除");
            } else {
                log.info("文件删除失败");
            }

        }catch (Exception e){
            log.error(e.toString());
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("msg","OCR识别失败");
            stringObjectHashMap.put("data",successList);
            return success(stringObjectHashMap);
        }
        return success("上传成功");
    }

效果展示

 

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Vue ElementUI文件上传前后端代码示例: 前端代码: ```vue <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button slot="trigger" size="small" type="primary">上传文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> <script> export default { methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); } if (!isLt500K) { this.$message.error('上传头像图片大小不能超过 500KB!'); } return isJPG && isLt500K; }, handleSuccess(res) { if (res.code === 0) { this.$message.success('上传成功'); } else { this.$message.error('上传失败'); } } } } </script> ``` 后端代码(Node.js Express框架): ```javascript const express = require('express'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); const app = express(); // 设置静态文件目录 app.use(express.static(path.join(__dirname, 'public'))); // 设置文件上传目录 const uploadPath = path.join(__dirname, 'uploads'); if (!fs.existsSync(uploadPath)){ fs.mkdirSync(uploadPath); } const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, uploadPath); }, filename: function (req, file, cb) { const extname = path.extname(file.originalname); const filename = Date.now() + extname; cb(null, filename); }, }); const upload = multer({ storage }); // 处理文件上传请求 app.post('/api/upload', upload.single('file'), function (req, res, next) { // 获取上传的文件信息 const file = req.file; if (!file) { return res.json({ code: 1, message: '上传失败' }); } console.log('文件上传成功:', file.filename); return res.json({ code: 0, message: '上传成功' }); }); // 启动服务器 const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` 以上代码示例中,前端代码使用了Vue ElementUI的el-upload组件实现文件上传,设置了文件类型和大小的限制,并通过axios发送文件上传请求。后端代码使用了Node.js的Express框架和multer中间件处理文件上传请求,将上传的文件保存到指定目录中,并返回上传结果和文件信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值