java下载文件工具类
public void getFileStream(String fileId, HttpServletResponse response) throws IOException{ List<PwFileInfoTablePO> byIds = pwFileInfoTableService.getByIds(Lists.newArrayList(fileId)); StringUtils.isTrueReMsg(StringUtils.isListEmpty(byIds),"文件未找到"); PwFileInfoTablePO pwFileInfoTablePO = byIds.get(0); File ossObjectToFile = getOSSObjectToFile(pwFileInfoTablePO.getInternetRegionOssid(), pwFileInfoTablePO.getInternetRegionOssid()); try(ServletOutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(ossObjectToFile)){ response.addHeader("Content-Disposition", "attachment;filename=" +pwFileInfoTablePO.getFileName()); response.setContentType("application/octet-stream"); IOUtils.copy(fileInputStream,outputStream); } }
java下载文件工具类
package com.skjd.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
public class DownloadUtils {
/**
* 根据网络url下载文件
* 下载到指定文件
* @throws MalformedURLException
*/
public static void DownloadByUrlToFile(String urlPath,String filename2) throws Exception{
URL url = new URL(urlPath);
/* //文件后缀名
String str = url.getFile().substring( url.getFile().lastIndexOf(".")+1);
//文件名
String filename = url.getFile().substring(url.getFile().lastIndexOf("/")+1,url.getFile().lastIndexOf("."));*/
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int code = conn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
InputStream fis = new BufferedInputStream(conn.getInputStream());
File file = new File(filename2);
OutputStream toClient = new BufferedOutputStream(new FileOutputStream(file));
// 以流的形式下载文件。
byte[] buffer = new byte[1024*8];
int read=0;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-1) {
//读取多少输出多少
toClient.write(buffer,0,read);
}
toClient.flush();
toClient.close();
fis.close();
}
/**
* 根据网络url下载文件
* 直接返回给浏览器
* @throws MalformedURLException
*/
public static void DownloadByUrl(String urlPath,HttpServletResponse response) throws Exception{
URL url = new URL(urlPath);
//文件后缀名
String str = url.getFile().substring( url.getFile().lastIndexOf(".")+1);
//文件名
String filename = url.getFile().substring(url.getFile().lastIndexOf("/")+1,url.getFile().lastIndexOf("."));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int code = conn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
InputStream fis = new BufferedInputStream(conn.getInputStream());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" +filename+"."+str);
response.setContentType("application/octet-stream");
// 以流的形式下载文件。
byte[] buffer = new byte[1024*8];
int read=0;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-1) {
//读取多少输出多少
toClient.write(buffer,0,read);
}
toClient.flush();
toClient.close();
fis.close();
}
}
使用案例代码
/**
* 导出购票码
*/
@RequestMapping(value="/getAllCode")
public void getAllCode(HttpServletResponse response){
PageData pd = new PageData();
pd = this.getPageData();
try {
List<PageData> list = driverService.listAll(pd);
//获取当前项目的绝对路径
String realPath = this.getRequest().getSession().getServletContext().getRealPath("/");
File file = new File(realPath+"/codes/");
//判断是否存在这个文件夹,如果不存在则重新创建一个文件
if(!file.exists()){
file.mkdirs();
}
String url2="";
List<PageData> list3 = dictionariesService.getIMGUrl(null);
for(int i=0;i<list3.size();i++){
if(String.valueOf(list3.get(i).get("remarks")).length()>6){
url2=String.valueOf(list3.get(i).get("remarks"));
}
}
for(int i=0;i<list.size();i++){
if(list.get(i).get("code_url")!=null&&!"".equals(String.valueOf(list.get(i).get("code_url")))){
DownloadUtils.DownloadByUrlToFile(url2+String.valueOf(list.get(i).get("code_url")),realPath+"/codes/"+String.valueOf(list.get(i).get("idcode"))+".png");
}
}
FileZip.zip(realPath+"/codes/", realPath+"/codes.zip");
InputStream fis = new BufferedInputStream(new FileInputStream(new File(realPath+"/codes.zip")));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
Cookie cookie = new Cookie("abcd", "123");
cookie.setPath("/");
response.addCookie(cookie);
// 设置response的Header
response.setContentType("application/zip");// 指明response的返回对象是文件流
response.setHeader("content-Disposition", "attachment;filename=codes.zip");// 设置在下载框默认显示的文件名
// 以流的形式下载文件。
byte[] buffer = new byte[1024*8];
int read=0;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-1) {
//读取多少输出多少
toClient.write(buffer,0,read);
}
toClient.flush();
toClient.close();
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void downLoadFile(HttpServletResponse response, String filePath) throws IOException { File file = new File(filePath); downLoadFile(response,file); } public static void downLoadFile(HttpServletResponse response,File file) throws IOException { if (file.exists()) { response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); byte[] buffer = new byte[1024]; try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) { OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } fis.close(); os.close(); } } } public static void downLoadFile(HttpServletResponse response,InputStream fis,String fileName) throws IOException { response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buffer = new byte[1024]; try ( BufferedInputStream bis = new BufferedInputStream(fis)) { OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } fis.close(); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?