后端

单个文件下载

package com.ruoyi.common;

import com.ruoyi.project.system.domain.TSystemFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 下载功能
 *
 * @author DELL
 */
@RestController
@RequestMapping("/system/downLoad")
public class DownLoadFileTools {

    @GetMapping("/downLoadFile")
    public void downLoadFile(TSystemFile tSystemFile, HttpServletResponse response) throws Exception {
        long starttime = System.currentTimeMillis();
        String path = tSystemFile.getFilepath();
        String filename = tSystemFile.getFilename();
        URL url = new URL(path);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();
        response.reset();
        //文件类型自动判断
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("UTF-8");
        //将Content-Disposition暴露给前端
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //将文件名放入header的Content-Disposition中
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));


        byte[] buffer = new byte[1024 * 1024 * 10];
        int len;

        BufferedOutputStream outputStream =new BufferedOutputStream(response.getOutputStream()) ;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
        long endtime = System.currentTimeMillis();
        System.out.println("下载时间为:"+(endtime-starttime)/1000+"秒");
    }


}

多个图片zip下载

 //如果是多个文件,打成zip在下载
                String fileName="图片.zip";
                response.reset();
                //文件类型自动判断
                response.setContentType("multipart/form-data");
                response.setCharacterEncoding("UTF-8");
                //将Content-Disposition暴露给前端
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                //将文件名放入header的Content-Disposition中
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                //创建压缩流关联压缩包  ZipOutputStream类:完成文件或文件夹的压缩
                ZipOutputStream zos=new ZipOutputStream(response.getOutputStream());
                for (UpFile file:files) {
                    URL url=new URL(file.getViewpath());
                    URLConnection conn = url.openConnection();
                    InputStream inputStream=conn.getInputStream();
                    //创建ZipEntry对象,并为每个文件命名,放入压缩包当中
                    ZipEntry ze=new ZipEntry(file.getFilename());
                    zos.putNextEntry(ze);
                    byte[] buffer = new byte[1024 * 1024 * 10];
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                    inputStream.close();
                    zos.closeEntry();
                }
                zos.close();

前端

 <el-upload
              class="upload-demo"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>  


//点击附件名称触发
  handlePreview(file) {
        console.log(file)
        var msg = {filepath: file.url, filename: file.name}
        downloadFileTools(msg).then(res=>{
      console.log(res, 'ress')
     const blob = new Blob([res.data], {type: res.data.type})
    const downloadElement = document.createElement('a')
    //  var url=window.URL || window.webkitURL || window.moxURL;
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    var fileName = result[1]
    fileName = fileName.replace(/\"/g, '')
    downloadElement.download = fileName
    downloadElement.click()

        })
      },
export function downloadFileTools(query) {
  return request({
    url:'/system/downLoad/downLoadFile',
    method:'get',
    responseType:'blob',
    params:query
  })
}

还需要在响应拦截中添加一行判断返回整个response,不然获取不到header

Logo

前往低代码交流专区

更多推荐