在你瀟灑的寫下InputStream轉到response的時候,需要先設置下Response,否則瀏覽器並不會彈出下載框
預處理
"Content-Type", "application/octet-stream"
是內容類型,告訴瀏覽器這個是什麼,可以參照對照表
https://www.runoob.com/http/http-content-type.html
public static void preInitResponseForFileStream(HttpServletResponse response, String name) {
response.reset();
//避免中文亂碼
response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), StandardCharsets.ISO_8859_1));
response.setHeader("Connection", "close");
//設置傳輸的類型
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Transfer-Encoding", "chunked");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/OCTET-STREAM");
}
下載
這裏也順便把下載貼上來吧,也可以使用其他流的處理方式,比如java7的Files
工具類等,或者apache的IOUtils
public static void download(String fileUrl, HttpServletResponse response) {
try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
out.write(dataBuffer, 0, bytesRead);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}