Java知识分享(spring全家桶、面试突击)
每天进步一点点
为什么要写这篇文章呢?生产bug!!!
Beta环境下,点击:图片可以展示图片,文件直接下载
图片1
生产环境下,图片地址是公网,外网下没有访问权限,功能不正常。所以改用流的方式去获取网络资源。
下载文件
/**
* @param contract
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/downLoadFile")
public void downLoadFile(String contract, HttpServletResponse response) throws Exception {
log.info("CreateZoneController downLoadFile contract:" + contract);
try {
//获取文件名
String fileName = contract.substring(contract.lastIndexOf("/")+1);
fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
log.info("CreateZoneController downLoadFile fileName:" + fileName);
long beginTime = System.currentTimeMillis();
HttpFileDownLoad.downLoadFromUrl(contract, fileName, response);
log.info("CreateZoneController downLoadFile success cosTime: {}", (System.currentTimeMillis()-beginTime));
} catch (Exception e) {
log.error("CreateZoneController downLoadFile" );
}
}
http文件下载
/**
* http文件下载
*
* @author zhoudoujun01
* @date 2019年12月18日14:58:17
*/
public class HttpFileDownLoad {
private static final Logger log = LogManager.getLogger(HttpFileDownLoad.class);
/**
* 从网络Url中下载文件
*
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void downLoadFromUrl(String urlStr, String fileName, HttpServletResponse response) throws IOException {
InputStream inputStream = null;
ServletOutputStream responOutPut = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// conn.setRequestProperty("lfwywxqyh_token",toekn);
// 得到输入流
inputStream = conn.getInputStream();
responOutPut = response.getOutputStream();
// 设置下载文件头及文件名称
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// 流写出
byte[] buffer = new byte[1024 * 100];
int i = 0;
while ((i = inputStream.read(buffer)) > 0) {
responOutPut.write(buffer, 0, i);
}
responOutPut.flush();
} catch (Exception e) {
log.error("HttpFileDownLoad downLoadFromUrl error: {}", e);
} finally {
if (inputStream != null) {
inputStream.close();
}
if(responOutPut != null) {
responOutPut.close();
}
}
}
}
jsp页面
<a href="<%=basePath%>createZone/downLoadFile?contract=${zoneInfo.contract }" target="_blank" style="color:blue">图片1</a>