SpringMvc檔案下載
1.單個檔案的下載。
@RequestMapping("/downLoad")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
String resourceName = "test.txt";
File file = new File("D:/"+resourceName);
HttpHeaders headers = new HttpHeaders();
String filename = new String(resourceName.getBytes("utf-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
}
2.多個檔案的下載
思路:將多個需要下載的檔案壓縮成1個檔案進行下載。
壓縮流的使用
String pathname = "D:/test.zip";
File file = new File(pathname);
/*if(!file.exists()) {
file.createNewFile();
}*/
OutputStream out = new FileOutputStream(file);
ZipOutputStream output = new ZipOutputStream(out);
InputStream in = null;
File temp = new File("D:/test.txt");
System.out.println(temp.getName());
output.putNextEntry(new ZipEntry(temp.getName()));
in = new FileInputStream(temp);
int i = 0 ;
while((i=in.read())!=-1){ // 讀取內容
output.write(i) ; // 壓縮輸出
}
in.close() ; // 關閉輸入流
output.close() ;
批量下載
//批量檔案壓縮後下載
@RequestMapping("/downLoad2")
public ResponseEntity<byte[]> download2(HttpServletRequest request) throws IOException {
//需要壓縮的檔案
List<String> list = new ArrayList<String>();
list.add("test.txt");
list.add("test2.txt");
//壓縮後的檔案
String resourcesName = "test.zip";
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:/"+resourcesName));
InputStream input = null;
for (String str : list) {
String name = "D:/"+str;
input = new FileInputStream(new File(name));
zipOut.putNextEntry(new ZipEntry(str));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
}
zipOut.close();
File file = new File("D:/"+resourcesName);
HttpHeaders headers = new HttpHeaders();
String filename = new String(resourcesName.getBytes("utf-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
---------------------
作者:qq_33422712
來源:CSDN
原文:https://blog.csdn.net/qq_33422712/article/details/79142350
版權宣告:本文為博主原創文章,轉載請附上博文連結!