优化代码@PostMapping("/downInvoices4") public void downInvoices4(@RequestBody List<String> pathList,HttpServletResponse response) { String UUIDStr = String.valueOf(UUID.randomUUID()); String folderName = "invoice" + UUIDStr.replace("-",""); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename="+folderName+".zip"); try { URL url = new URL(pathList.get(0)); URLConnection coon = url.openConnection(); InputStream is = coon.getInputStream(); ServletOutputStream sos = response.getOutputStream(); ZipInputStream zis = new ZipInputStream(is); ZipEntry zipEntry =zis.getNextEntry(); ZipOutputStream zos = new ZipOutputStream(sos); zos.putNextEntry(zipEntry); zos.closeEntry(); IoUtils.copy(zis,zos); zos.close(); zis.close(); sos.close(); is.close(); } catch (Exception e) { throw new RuntimeException(e); } }
时间: 2024-03-02 16:52:33 浏览: 26
这段代码可以进行一些优化:
1. 首先,建议将该方法的返回类型改为 ResponseEntity<byte[]>,这样可以更好地控制响应的内容。同时,也可以避免一些潜在的问题,比如下载文件时可能会出现乱码的情况。
2. 接着,可以将生成文件名和设置响应头的代码提取出来,作为一个单独的方法。这样可以提高代码的可读性和复用性。
3. 然后,可以使用 try-with-resources 语句来自动关闭流,避免出现资源泄漏的情况。
4. 最后,建议对输入参数进行必要的校验,比如判断 pathList 是否为空,以及其中是否包含有效的 URL。
下面是优化后的代码示例:
```
@PostMapping("/downInvoices4")
public ResponseEntity<byte[]> downInvoices4(@RequestBody List<String> pathList) {
validate(pathList); // 校验输入参数
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
for (String path : pathList) {
URL url = new URL(path);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
ZipEntry entry = new ZipEntry(getFileName(path));
zos.putNextEntry(entry);
IoUtils.copy(is, zos);
zos.closeEntry();
is.close();
}
zos.close();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDisposition(ContentDisposition.attachment().filename(getZipFileName()).build());
return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void validate(List<String> pathList) {
if (pathList == null || pathList.isEmpty()) {
throw new IllegalArgumentException("pathList cannot be null or empty");
}
for (String path : pathList) {
try {
new URL(path);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid URL: " + path);
}
}
}
private String getFileName(String path) {
int index = path.lastIndexOf("/");
return index >= 0 ? path.substring(index + 1) : path;
}
private String getZipFileName() {
String UUIDStr = String.valueOf(UUID.randomUUID());
String folderName = "invoice" + UUIDStr.replace("-", "");
return folderName + ".zip";
}
```