public class FileUtils {
/**
* realPath 磁盘路径 D://project/download/
* urlPath 后半部分路径 具体根据业务需求,例如:WEB-INF/download.xlsx
* downLoadName 下载后的新名字
* @param request
* @param resp
*/
public static void downloadFromDisk(HttpServletRequest request, HttpServletResponse resp,String realPath,String urlPath,String downLoadName) {
//文件最终路径,例如:D://project/download/WEB-INF/download.xlsx
String path = realPath + File.separator + urlPath;
File file = new File(path);
if(!file.exists()){
System.out.println("---------<系统找不到指定的文件>---------");
return;
}
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
//下载到本地的文件名,例如:abc.xlsx(注意:这里跟路径中的文件名区分开)
String downloadName = downLoadName;
resp.setHeader("Content-Disposition", "attachment;filename=" + downloadName );
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
System.out.println("---------<文件下载成功>---------");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void downloadFromIntNet(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为5秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//创建保存路径
File saveDir = new File(savePath);
if(!saveDir.exists()) {
saveDir.mkdir();
}
//创建文件
File file = new File(saveDir+File.separator+fileName);
//文件输出流
FileOutputStream fout = new FileOutputStream(file);
//输出文件
byte[] buff = new byte[4096];
int len = -1;
while ((len = inputStream.read(buff)) != -1) {
fout.write(buff,0,len);
}
//关闭输出输入流
fout.close();
inputStream.close();
System.out.println("info:"+url+" download success");
}
}
----------------------------------调用---------------------------------------
/*从磁盘下载*/
String realPath = "C:\files\images";
String urlPath = "user.png";
String downLoadName = "newname.png";
FileUtils.downloadFromDisk(request,resp,realPath,urlPath,downLoadName);
/*从网络下载*/
String path = "http://yourIP:yourPort/files/201111/images/2019/12/24/2019122409504998593372629015.jpg";
FileUtils.downloadFromIntNet(path,"test.jpg","C:\myfile\images");