第一种
public Response downLoadFile(String urlString){ String[] fileName = urlString.split("/"); try (InputStream inputStream =new URL(URLDecoder.decode(urlString, "utf-8")).openStream()){ byte[] b = inputStream.readAllBytes(); return Response.ok(b) .header("Content-Disposition", "attachment;filename=" + fileName[fileName.length-1]) .header("Content-Length", b.length) .build(); } catch (IOException e) { LOG.error("download template failed, exception is:", e); throw new ServiceOperationException(ServiceError.DOWNLOAD_FILE_FAILED); } }
第二种 :
public Response downLoadFile(String urlString){ String[] fileName = urlString.split("/"); Response.ResponseBuilder response = Response.ok( (StreamingOutput) output -> { try (InputStream content =new URL(URLDecoder.decode(urlString, "utf-8")).openStream()) { if (content != null) { byte[] b = new byte[2048]; int length; while ((length = content.read(b))!= -1) { output.write(b, 0, length); } } } catch (IOException e) { LOG.error("download file failed, exception", e); throw new ServiceOperationException(ServiceError.DOWNLOAD_FILE_FAILED); } }); response.header("Content-Disposition", "attachment;filename=" + fileName[fileName.length - 1]); return response.build(); }
第一种可正常下载文件,第二种汇报序列化错误,具体错误如下:
2022-04-25 14:57:36,121 INFO [res.log] (executor-thread-0) [Response] POST /v1/api/applet/download with result: OK, elapsed: 22.28 ms, req-id: 1234 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: org.jboss.resteasy.core.providerfactory.SortedKey 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: io.quarkus.resteasy.common.runtime.jackson.QuarkusJacksonSerializer 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: io.quarkus.resteasy.common.runtime.jackson.QuarkusJacksonSerializer 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: org.jboss.resteasy.core.providerfactory.SortedKey 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) Interceptor Context: org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext, Method : proceed
先记录下问题,后续解决再更新
第一种:直接把所有字节读入内存
第二种:边读边写