话不多说,直接上代码!!!!
复制以下代码到你的程序中:
/**
* 规章制度-下载pdf文件
* @param url
* @param response
* @throws UnsupportedEncodingException
*/
@RequestMapping(value="/download")
public @ResponseBody void invoiceDownload(String url,HttpServletResponse response ) throws UnsupportedEncodingException{
ServletOutputStream out = null;
InputStream ips = null;
URL oracle = null;
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.isNotEmpty(fileName)) {
int offset = fileName.lastIndexOf("/");
if (offset != -1 && offset != fileName.length() - 1) {
ext = fileName.substring(offset + 1);
}
}
return ext.toLowerCase();
}
layui调用接口并传参url即可。
<a href="/api2/standard/download?url={{d.documentUrl!=null?d.documentUrl:null}}" style="cursor:pointer;">下载</a>
效果图:
原文转载:原文转载