HttpURLConnection 文件下载转发细节
细节:outputStream对象必须在inputStream对象之前创建,否则会引起bug(即用户第一次点击发起下载请求会一直等待, 必须再次点击才能下载)
使用的是springMVC,下载文件的action如下
@RequestMapping("/report_generalPdf")
public void downloadFile(@RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) {
if (filePath != null) {
response.addHeader("Content-Disposition",
"attachment;fileName=" + "result.pdf");// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
// 测试用的内网资源
URL url = new URL("http://192.168.xxx.xx/uploadFiles/report/xxx/xxx/xxx_report.pdf");
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
httpURLConnection.setConnectTimeout(100);
httpURLConnection.setReadTimeout(100);
// 文件大小
// int fileLength = httpURLConnection.getContentLength();
// 文件名
// String filePathUrl = httpURLConnection.getURL().getFile();
// String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
// System.out.println("file length---->" + fileLength);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
bis = new BufferedInputStream(httpURLConnection.getInputStream());
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}