前端使用vue点击上传文件,传送给后端,后端进行文件接收

一、效果图

前端页面:

在java这边后端的target文件就可以接收到前端发送的文件,文件可以打开

接下来看具体代码是怎么实现的!

二、代码部分

Vue代码

<template>  
  <el-upload  
    ref="upload"  
    class="upload-demo"  
    action="http://localhost:9090/api/upload"  <!--这个为后端响应的路径-->
    :on-success="handleSuccess"  
    :before-upload="beforeUpload"  
    :file-list="fileList"  
    :auto-upload="false"  
    :on-change="handleChange"  
  >  
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>  
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>  
    <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件,且不超过500kb</div>  
  </el-upload>  
</template>  
  
<script>  
export default {  
  // ... 其他代码保持不变  
  data() {  
    return {  
      fileList: []  
    };  
  },  
  methods: {  
    handleSuccess(response, file, fileList) {  
      console.log('文件上传成功:', response);  
    },  
    beforeUpload(file) {  
      // 限制格式为excel
      // 如果不想限制可以将这行代码去掉,以及后面的一些关于excel的判断
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';  
      // 限制文件大小
      const isLt2M = file.size / 1024 / 1024 < 0.5;  

      if (!isExcel) {  
        this.$message.error('上传文件只能是 xls/xlsx 格式!');  
      }  

      if (!isLt2M) {  
        this.$message.error('上传文件大小不能超过 500KB!');  
      }  
      return isExcel && isLt2M;  
    },  
    submitUpload() {  
      // 这边的$refs.upload要与上面第三行的ref一致
      this.$refs.upload.submit();  
    },  
    handleRemove(file, fileList) {  
      console.log('移除文件', file, fileList);  
    },  
    handleChange(file, fileList) {  
      this.fileList = fileList;  
    }  
  }    
};  
</script>

后端代码

(1)首先导入依赖
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
    </dependency>
(2)controller层(也可以在servlet写)
@RequestMapping(value = "/upload")
    public void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{
        // 检查请求是否为多部分请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new ServletException("Content type is not multipart/form-data");
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        //下面的路径就是你要映射到target的路径
                        String filePath = request.getServletContext().getRealPath("/") + "WEB-INF"+File.separator+"static" + File.separator + fileName;
                        File storeFile = new File(filePath);

                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        System.out.println("编码前的原文: " + fileName);
                        //这一条在控制台打印可能会出现字符编码的问题,如浣撴浜哄憳淇℃伅.xlsx
                        //这种是gbk编码,接下来就将gbk解码为utf-8
                        byte[] gbkBytes = fileName.getBytes("gbk");
                        for (byte b : gbkBytes) {
                            System.out.print(Integer.toHexString(b & 0xff) + ",");
                        }
                        String gbkToUtf8 = new String(gbkBytes, "utf8");
                        System.out.println("gbk编码,utf8解码后的文字: " + gbkToUtf8 + "\n" + "----------------------");
                       

                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message", "文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message", "文件上传失败!");
        }
    }

这样子字符编码就不会出现乱码 

这样子写就可以实现上面的那种效果啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值