webFlux 文件下载以及问题处理

1. webFlux 的下载

首先 webflux中没有HttpServletResponse,但是在webflux中提供了org.springframework.http.server.reactive.ServerHttpResponse,但是在注入的时候要注意自己的项目中的jar包,不然在将ServerHttpResponse转换为同样继承了 ReactiveHttpOutputMessage的类ZeroCopyHttpOutputMessage,spring在注入ServerHttpResponse可能会将其注入为其他的,像我就遇到了这个问题

 这是我遇到的问题信息

java.lang.ClassCastException: org.springframework.http.server.reactive.TomcatHttpHandlerAdapter$TomcatServerHttpResponse cannot be cast to org.springframework.http.ZeroCopyHttpOutputMessage
	at com.rbs.apisix.controller.EnvFileController.exportExcel(EnvFileController.java:120)
	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
   <!--统一处理工具类-->
        <dependency>
            <groupId>com.rbs</groupId>
            <artifactId>common-tool</artifactId>
            <version>1.0.7</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat.embed</groupId>
                    <artifactId>tomcat-embed-core</artifactId>
                </exclusion>
                 <exclusion>
                     <groupId>org.apache.httpcomponents</groupId>
                     <artifactId>httpclient</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>

 然后是文件下载的代码,我这里写的可能多了点

  public Mono<Void> export(ServerHttpResponse response) {
        ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
      
        String fileName = System.currentTimeMillis() + ".txt";
        File finalFile = null;
        try {
            String content ="测试文件导出";
            HttpHeaders headers = zeroCopyResponse.getHeaders();
            headers.set("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            headers.set("file-name", URLEncoder.encode(fileName, "UTF-8"));
            headers.set("Access-Control-Allow-Origin", "*");
            MediaType application = new MediaType("application", "octet-stream", Charset.forName("UTF-8"));
            headers.setContentType(application);
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = content.getBytes("UTF-8");
            fout.write(bytes);
            fout.close();
            finalFile = new File(fileName);
            zeroCopyResponse.writeWith(finalFile, 0, finalFile.length()).subscribe();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (finalFile != null) {
                finalFile.delete();
            }
        }

        return null;
    }

然后还有一种写法是直接使用的ServerHttpResponse,这种我只是测试了下

public Mono<ServerResponse> test() throws IOException {
    String content = JSON.toJSONString("test");
    FileOutputStream fout = new FileOutputStream("test.txt");
    byte[] bytes = content.getBytes("UTF-8");
    fout.write(bytes);
    fout.close();
   File finalFile = new File("test.txt");
return     ServerResponse.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=test.txt")
            .contentType(new MediaType("multipart/form-data"))
            .body((p, a) -> {
                ZeroCopyHttpOutputMessage resp = (ZeroCopyHttpOutputMessage) p;
                return resp.writeWith(finalFile, 0, finalFile.length());
            }).doFinally(a -> {finalFile.delete();});
}

2. webFlux 的文件上传

我就只贴出部分代码了,这里使用@RequestPart注解接收文件,然后FilePart .transferTo()能够将文件转换为file至于之后的操作就要看你的业务要求了

   public Mono<CommonResult<String>> exportImport(@RequestPart("file") FilePart file) throws IOException, InvalidFormatException, IllegalAccessException, InstantiationException {
        File file1 = new File(file.filename());
        file.transferTo(file1);
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值