public HttpServletResponse download(HttpServletRequest request, HttpServletResponse response) {
try {
//獲取附件名稱
String fileName = request.getParameter("fileName");//檔案名稱
// 獲取路徑
String path =FILE_URL + DOMESTIC_SMS_SEND_TEMPLATE_URL;
URL url = new URL(path + URLEncoder.encode(fileName,"utf-8"));
HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
httpConn.setDoOutput(true);// 使用 URL 連接進行輸出
httpConn.setDoInput(true);// 使用 URL 連接進行輸入
httpConn.setUseCaches(false);// 忽略快取
httpConn.setRequestMethod("GET");// 設定URL請求方法
//可設定請求頭
httpConn.setRequestProperty("Content-Type", "application/octet-stream");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連接
httpConn.setRequestProperty("Charset", "UTF-8");
//可設定請求頭
byte[] b =input2byte(httpConn.getInputStream());
response.reset();
// 設定response的Header
String userAgent = request.getHeader("User-Agent").toLowerCase();
//chrome頭也包含safari,需要排除chrome
if(userAgent.contains("safari") && !userAgent.contains("chrome")){
//處理safari的亂碼問題
byte[] bytesName = fileName.getBytes("UTF-8");
fileName = new String(bytesName, "ISO-8859-1");
response.setHeader("Content-Disposition",
"attachment; filename="+ new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
}else{
response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
}
//response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
//response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(b);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}finally {
logger.info("------下載模板完成---");
}
return null;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/244383.html
標籤:Java相關
上一篇:java畫圖方法
