通过url下载文件:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getRequest(HttpServletResponse response) {
String requestPath = "http://xxx.com/demo/sys/test.pdf"
String filename = "test.pdf";
InputStream inputStream = null;
OutputStream out = null;
File file = null;
try {
file = new File(filename);
URL url =new URL(requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// conn.setConnectTimeout(1000);//超时提示1秒=1000毫秒
FileUtils.copyURLToFile(url, file);
// inputStream = conn.getInputStream();//获取输出流
response.setHeader("Content-Disposition", "attachment" + ";filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
byte[] bytes = new byte[(int)file.length()];
inputStream = new FileInputStream(file);
out = response.getOutputStream();
out.write(bytes, 0, inputStream.read(bytes));
} catch (Exception e) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file != null && file.exists()) {
file.delete();
}
}
}
下载本地文件:
@RequestMapping(value = "download",method = RequestMethod.GET)
public ResponseEntity<byte[]> download(HttpServletResponse response, HttpServletRequest request) throws Exception{
//预下载文件路径******
String preDownload_path = "C:/Users/Administrator/Desktop/Learn/pdf/temp8.pdf";
int index = preDownload_path.lastIndexOf("/");
//下载后的文件名
String downloadName = preDownload_path.substring(index+1);
System.out.println(index);
System.out.println(downloadName);
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(downloadName,"UTF-8"));
FileInputStream is = null;
OutputStream os = null;
try {
URL url = new URL(preDownload_path);
is = new FileInputStream(String.valueOf(url.openStream()));
// is = new FileInputStream(new File(preDownload_path));
os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
os.close();
is.close();
}
return null;
}