导出下载公共方式(后台返回文件流或文件地址)

本文介绍如何通过API接口下载不同类型的文件,包括普通文件流、blob类型数据和跨域文件下载的方法,重点讲解了Blob对象的使用和处理跨域下载的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下方法是后台返回文件流(从文件头里取类型,可下载任何类型的文件)

接口请求

下载一般类型:

/**
 * download file下载文件
 */
export const downloadBlobFile = (res, fileNameS) => {
  if (!res) {
    return
  }
  let contentType = res.headers['content-type'];
  const blob = new Blob([res.data], {
    type: contentType
  })
  let fileName = ''
  if(fileNameS) {
    fileName = `${fileNameS}`
  } else {
    fileName = res.headers['content-disposition'] ? decodeURI(escape(res.headers['content-disposition'].split(';')[1].split('=')[1])) : '';
  }
  debugger
  let a = document.createElement("a");
  let url = window.URL.createObjectURL(blob);
  console.log(blob)
  a.setAttribute("href", url)
  a.download = fileName
  document.body.appendChild(a);
  a.click()
  document.body.removeChild(a);
}

下载blobjson类型:

// 下载bolbjson
export const downloadBlobJson = (data, fileNameS = 'json') => {
  if (!data) {
    return
  }
  // console.log(data)
  const blob = new Blob([JSON.stringify(data)])
  const fileName = `${fileNameS}.json`
  if ('download' in document.createElement('a')) { // 不是IE浏览器
    const url = window.URL.createObjectURL(blob)    
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(url) // 释放掉blob对象
  } else { // IE 10+
    window.navigator.msSaveBlob(blob, fileName)
  }
}

 

 

以下方法是后台返回文件地址

一般文件的导出: 

 /**
 * @param attachPath  导出路径
 * @return 导出文件
 */
export const downloadFile =(attachPath)=> { 
    var $a = document.createElement('a');
    $a.setAttribute("href", attachPath);
    $a.setAttribute("download", "");
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
    $a.dispatchEvent(evObj);
}

 跨域文件导出下载方法

 /**
 * @param url  导出路径
 * @param fileName  文件名
 * @return 跨域文件路径、下载到本地的文件名
 */
export const downloadFileBlob =(url,fileName)=> { 
    var x = new XMLHttpRequest();
    x.open("GET", url, true);
    x.responseType = 'blob';
    x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
    }
    x.send();
}

 

<think>好的,我需要帮助用户寻找Java中实现异步导出任务的公共方法。首先,我需要理解用户的需求。用户想要一个通用的工具方法,用于异步导出任务,可能在后台处理数据生成,避免阻塞主线程。常见的实现方式可能涉及线程池、异步框架者Spring的@Async注解。 接下来,我要回忆Java中处理异步任务的常用方法。线程池是一个基础的方式,可以使用ExecutorService来提交任务。另外,如果用户的项目使用了Spring框架,那么@Async注解会是一个更简洁的选择。CompletableFuture也是Java 8之后推荐的异步编程方式,可以结合使用。 然后,我需要考虑如何将这些方法封装成公共的实用工具类。可能需要设计一个ExportUtils类,里面包含静态方法,接收导出任务的参数,比如数据生成逻辑、回调处理等。同时,需要处理异常情况,确保任务失败时有适当的日志记录回调通知。 用户提供的引用中有提到异步操作不等待测试的情况,这可能涉及到任务提交后立即返回,但需要确保任务被正确调度和执行。例如,引用[1]中提到在测试中不等待异步操作,但需要验证按钮状态,类似地,导出任务提交后可能需要返回任务ID状态,让调用方可以轮询接收回调。 另外,引用[3]提到使用模拟数据,可能导出任务需要生成大量数据,异步处理可以避免前端长时间等待。引用[5]中的Node.js示例使用require引入模块,可能在Java中需要类似的工具类结构,确保方法可重用。 然后,我需要确保代码示例的正确性。比如,使用Spring的@Async需要配置异步支持,线程池的参数需要合理设置,避免资源耗尽。同时,处理CompletableFuture时要注意异常处理和链式调用。 可能还需要考虑任务的状态跟踪,比如返回一个Future对象,让调用方可以查询任务是否完成,者获取结果。此外,日志记录和错误处理也是关键,确保导出任务中的异常能被捕获并处理,而不是默默失败。 最后,生成相关问题需要考虑用户可能遇到的扩展需求,比如如何监控任务进度、如何处理大数据量导出、如何保证任务顺序等。这些问题可以帮助用户进一步优化他们的异步导出实现。</think>### Java异步导出任务实现方法 在Java中实现异步导出任务,可通过线程池Spring框架的异步支持实现。以下是两种常用方法及工具类封装: --- #### 方法一:使用线程池工具类(原生Java) ```java import java.util.concurrent.*; public class ExportUtils { private static final ExecutorService executor = Executors.newFixedThreadPool(4); // 根据需求调整线程数 /** * 提交异步导出任务 * @param task 导出任务逻辑(实现Callable接口) * @return Future对象用于获取任务状态/结果 */ public static <T> Future<T> asyncExport(Callable<T> task) { return executor.submit(task); } } // 使用示例 Future<File> exportFuture = ExportUtils.asyncExport(() -> { // 生成Excel/CSV等导出文件 return generateReport(); }); ``` --- #### 方法二:使用Spring框架的@Async注解 ```java import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; @EnableAsync @Component public class ExportAsyncService { /** * 异步导出方法 * @param params 导出参数 */ @Async("taskExecutor") // 指定自定义线程池 public void asyncExportData(Map<String, Object> params) { try { // 执行数据查询与文件生成 generateExportFile(params); } catch (Exception e) { // 异常处理逻辑 log.error("导出失败", e); } } } // 配置线程池(application.yml) spring: task: execution: pool: core-size: 5 max-size: 10 ``` --- #### 方法三:CompletableFuture实现(Java 8+) ```java public class ExportUtility { public static CompletableFuture<Void> asyncExport(Runnable task) { return CompletableFuture.runAsync(task, ForkJoinPool.commonPool()); // 可替换为自定义线程池 } } // 使用示例 ExportUtility.asyncExport(() -> { // 导出逻辑 exportService.processData(); }).thenRun(() -> System.out.println("导出完成")); ``` --- ### 关键设计要点 1. **状态跟踪**:返回Future/CompletableFuture对象用于查询任务状态 2. **异常处理**:通过`Future.get()`捕获异常使用异常回调 3. **资源隔离**:建议为IO密集型任务使用单独线程池[^1] 4. **进度通知**:可通过回调接口事件机制实现进度更新 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值