/**
* 電子發票下載
* @param url
* @param response
* @throws UnsupportedEncodingException
*/
@GetMapping(value="/cxfKp/download")
public void invoiceDownload(String url,HttpServletResponse response ) throws UnsupportedEncodingException{
ServletOutputStream out = null;
InputStream ips = null;
URL oracle = null;
url="http://invtest.nntest.cn/group1/M00/07/5D/wKjScF7hmCKAcesuAACUI5iT5Xk128.pdf";
try {
oracle = new URL(url);
} catch (MalformedURLException e1) {
e1.printStackTrace();
return ;
}
HttpURLConnection uc = null;
try {
uc = (HttpURLConnection) oracle.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
return ;
}
try {
uc.setDoInput(true);//設置是否要從 URL 連接讀取數據,默認爲true
uc.connect();
//文件名
String newFileName = fileName(url);
//newFileName="電子發票.pdf";//重命名電子發票
ips = uc.getInputStream();
response.setContentType("multipart/form-data");
//爲文件重新設置名字,採用數據庫內存儲的文件名稱
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(newFileName.getBytes("UTF-8"),"ISO8859-1") + "\"");
out = response.getOutputStream();
//讀取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
out.close();
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ;
}
/**
* 獲取文件名字
* @param fileName
* @return
*/
private String fileName(String fileName){
String ext = null;
if (StringUtils.isNotBlank(fileName)) {
int offset = fileName.lastIndexOf("/");
if (offset != -1 && offset != fileName.length() - 1) {
ext = fileName.substring(offset + 1);
}
}
return ext.toLowerCase();
}
java通過連接(url)下載pdf文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.