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;
      });
    },
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了提高Java文件上传的速度,我们可以使用多线程上传。以下是实现多线程上传的步骤: 1.将大文件分割成多个小文件,每个小文件的大小可以根据实际情况进行设置。 2.使用多线程同时上传这些小文件,可以使用Java的CompletableFuture来实现。 3.在服务器端,将这些小文件合并成一个大文件。 下面是一个Java多线程上传大文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; public class MultiThreadUpload { private static final int THREAD_NUM = 5; // 线程数 private static final int BUFFER_SIZE = 1024 * 1024; // 缓冲区大小 private static final String UPLOAD_URL = "http://example.com/upload"; // 上传地址 private static final String FILE_PATH = "/path/to/large/file"; // 大文件路径 public static void main(String[] args) throws IOException { File file = new File(FILE_PATH); long fileSize = file.length(); long blockSize = fileSize / THREAD_NUM + 1; // 每个线程上传的块大小 List<CompletableFuture<Void>> futures = new ArrayList<>(); for (int i = 0; i < THREAD_NUM; i++) { long start = i * blockSize; long end = Math.min(start + blockSize, fileSize); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { uploadBlock(file, start, end); } catch (IOException e) { e.printStackTrace(); } }); futures.add(future); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); System.out.println("Upload finished."); } private static void uploadBlock(File file, long start, long end) throws IOException { URL url = new URL(UPLOAD_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Content-Range", "bytes " + start + "-" + (end - 1) + "/" + file.length()); try (InputStream in = new FileInputStream(file); OutputStream out = conn.getOutputStream()) { byte[] buffer = new byte[BUFFER_SIZE]; long pos = 0; while (pos < start) { long n = in.skip(start - pos); if (n <= 0) { throw new IOException("Unexpected EOF"); } pos += n; } while (pos < end) { int n = in.read(buffer, 0, (int) Math.min(buffer.length, end - pos)); if (n < 0) { throw new IOException("Unexpected EOF"); } out.write(buffer, 0, n); pos += n; } } if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException("Failed to upload block: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值