1. 程式人生 > >java IOUtils copy and flush client

java IOUtils copy and flush client

HTTP請求頭提供了請求、響應或者其他的傳送實體的資訊,HTTP訊息頭用來準確描述正在獲取的資源、伺服器或者客戶端的行為,定義了HTTP事務中的具體操作引數。

幾個主要頭的作用:

(1)Content-Type:當前內容的MIME型別 ,伺服器告訴瀏覽器它傳送的的資料屬於什麼檔案型別

例如:response.setContentType("application/octet-stream;charset=UTF-8");用於下載各類檔案,application/octet-stream表示二進位制資料,text/html表示HTML,text/plain表示普通文字

(2)Content-Disposition:對已知MIME型別資源的描述,瀏覽器可以根據這個響應頭決定是對返回資源的動作,如:將其下載或是開啟。

檔名亂碼問題

response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"",java.net.URLEncoder.encode(filename, "UTF-8")));

(3)Expires:指定一個日期/時間,超過該時間則認為此迴應已經過期

response.setHeader("Expires", "0");

(4)Pragma:與具體的實現相關,這些響應頭可能在請求/迴應鏈中的不同時候產生不同的效果

response.setHeader("Pragma", "no-cache");

public static void handleDownloadAndDelete(String filePath,

HttpServletRequest request, HttpServletResponse response) {
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream()) {
String filename = file.getName();
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(filename, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(fis, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
FileUtils.deleteQuietly(file);
}


public static void handleDownloadNoDelete(String filePath,
HttpServletRequest request, HttpServletResponse response) {
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream()) {
String filename = file.getName();
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(filename, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(fis, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
}


public static void handleDownloadfromStream(InputStream inputStream,
String fileName, HttpServletRequest request,
HttpServletResponse response) {
try (ServletOutputStream outputStream = response.getOutputStream()) {
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"",
java.net.URLEncoder.encode(fileName, "UTF-8")));
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
logger.warn("handleDownload-Exception:", e);
}
}