文件上传与下载

文件上传与下载

1.文件上传

  1. 前端

    <el-form-item>
        <el-upload
            v-permission="{action:'importExcel'}"
            class="upload-demo"
            action="http://localhost:8088/bookInfo/uploadExcel"
            accept=".xlsx"
            :show-file-list="false"
            :on-success="uploadSuccess"
            >
         <el-button type="primary">导入Excel</el-button>
    	</el-upload>
    </el-form-item>
    
    //方法
    methods: {
                uploadSuccess(response, file, fileList){
                    if(response.resp_code === 0){
                        this.$message({
                            message: '上传成功!',
                            type: 'success'
                        });
                        this.addFormVisible = false;
                        this.getbookInfos();
                    }else{
                        this.$message({
                            message: '上传失败!',
                            type: 'error'
                        });
                    }
                }
    }
    
  2. 后端:创建filename的文件,把前端传递的mutipartfile的流下载到本地,然后Easyexcel读取本地的文件数据到数据库

    @RequestMapping(value="/uploadExcel",method= RequestMethod.POST)
        @ApiOperation(value = "导入excel", notes = "导入excel")
        public Result uploadExcel(MultipartFile file){
            try {
                //获取文件的输入流
                InputStream inputStream = file.getInputStream();
                // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
                // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
                String fileName = filepath+UUID.randomUUID().toString()+".xlsx";
                //创建文件
                File file1 = new File(fileName);
                FileUtils.copyToFile(inputStream,file1);
                EasyExcel.read(fileName, BookInfoVO.class, new DemoDataListener()).sheet().doRead();
                System.out.println(file);
                return Result.succeed("ok");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.failed("no");
            }
        }
    

    2.文件下载

    1. 前端:直接通过a标签下载

      <el-form-item>
      	<el-button type="success" @click="downloadExcel" v-permission="{action:'downloadExcel'}">
      		<a href="http://localhost:8088//bookInfo/downloadExcel">导出Excel</a>
          </el-button>
      </el-form-item>
      
    2. 后端:后端接受httpreponse,返回值为void,然后再response里面设置响应头等。

 @RequestMapping(value="/downloadExcel",method= RequestMethod.GET)
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public void downloadExcel(HttpServletResponse response){
        try {
            List<BookInfoVO> list = bookInfoMapper.selectListVo();
            // 导出excl
            String name = "书籍信息"+ System.currentTimeMillis() + ".xlsx";
            String fileName =  filepath+name;
            // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
            // 如果这里想使用03 则 传入excelType参数即可
            EasyExcel.write(fileName, BookInfoVO.class).sheet("书籍").doWrite(list);
            //创建excel下载的文件
            File file = new File(fileName);
            // 设置以流的形式下载文件,这样可以实现任意格式的文件下载
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition","attachment;filename="+new String(name.getBytes("UTF-8"), "iso-8859-1"));
            response.setContentLength((int) file.length());

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                byte[] buffer = new byte[128];
                int count = 0;
                while ((count = fis.read(buffer)) > 0) {
                    response.getOutputStream().write(buffer, 0, count);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.getOutputStream().flush();
                response.getOutputStream().close();
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
response.addHeader("Content-Disposition","attachment;filename="+new String(name.getBytes("UTF-8"), "iso-8859-1"));
注意:new String(name.getBytes("UTF-8"), "iso-8859-1"))避免下载的文件中文名出现乱码
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值