Java通过流下载文件以及相关优化

1、基础版,通过Buffer缓冲流下载

        final File file = new File(robotPath);
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
        response.setContentLength((int) file.length());
        final byte[] buffer = new byte[NUM1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            final OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
          }

2、升级版,通过FileChannel下载,下载速度更快。

        File file = new File(info.getAbsolutePath());
        /**
         * 中文乱码解决
         */
        String type = request.getHeader("User-Agent").toLowerCase();
        String fileName = null;
        try {
            if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
                /**
                 * 谷歌或火狐
                 */
                fileName = new String(fileInfo.getFileName().getBytes(charsetCode), "iso8859-1");
            } else {
                /**
                 * IE
                 */
                fileName = URLEncoder.encode(fileName, charsetCode);
            }
            // 设置响应的头部信息
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 设置响应内容的类型
            response.setContentType(fileName + "; charset=" + charsetCode);
            response.setContentLength((int) file.length());
            // 设置响应内容的长度
            response.setHeader("filename", fileName);
            //通过文件管道获取飞一般的下载速度
            WritableByteChannel writableByteChannel = Channels.newChannel(response.getOutputStream());
            FileChannel fileChannel = new FileInputStream(file.getAbsolutePath()).getChannel();
            fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
        } catch (Exception e) {
            System.out.println("执行downloadFile发生了异常:" + e.getMessage());
        }

3、前端使用vue3.0和axios

    downloadFileByConditions(row) {
      const that = this;
      this.downDialogProgress = true;
      debugger
      const url = '/com/wk/filesmanage/downloadFileController/downloadFileByConditions';
      const tempParam = {
        sid:row.sid,
        databaseType: row.databaseType,
        fileName: row.fileName,
        fileType: row.fileType,
        fileVersion: row.fileVersion,
        ownService: row.ownService
      }
      const param = JSON.stringify(tempParam);
      axios.post(url, param, {
        responseType: "arraybuffer", headers: {
          "Content-Type": "application/json;charset=utf-8"
        },
        onDownloadProgress(a) {
          const percent = (parseInt(a.loaded) / parseInt(a.total) * 100 ).toFixed(2);
          nextTick(() => {
            that.progressNum = percent;
          });
        }
      }).then(res => {// 处理返回的文件流
        let blob = new Blob(
            [res.data],
            {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
            });
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = res.headers.filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        that.downDialogProgress = false;
        that.progressNum = 0;
      });
    },

你可能感兴趣的:(java,文件下载)