Java后台Controller实现⽂件下载操作
代码
参数:
1.filePath:⽂件的绝对路径(d:\download\a.xlsx)
2.fileName(a.xlsx)
3.编码格式(GBK)
代码⽚.
//控制器
@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)
public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {
boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);
if(is)
System.out.println("成功");
else
System.out.println("失败");
}
//下载⽅法
public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){  File f = new File(filePath);
if (!f.exists()) {
try {
response.sendError(404, "File not found!");
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
String type = fileName.substring(fileName.lastIndexOf(".") + 1);
//判断下载类型 xlsx 或 xls 现在只实现了xlsx、xls两个类型的⽂件下载
if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){
response.setContentType("application/force-download;charset=UTF-8");
final String userAgent = Header("USER-AGENT");
try {
if (ains(userAgent, "MSIE") || ains(userAgent, "Edge")) {// IE浏览器
fileName = de(fileName, "UTF8");
} else if (ains(userAgent, "Mozilla")) {// google,⽕狐浏览器
fileName = new Bytes(), "ISO8859-1");
} else {
fileName = de(fileName, "UTF8");// 其他浏览器
}
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
} catch (UnsupportedEncodingException e) {
<(e.getMessage(), e);
return false;
}
InputStream in = null;
OutputStream out = null;
try {
//获取要下载的⽂件输⼊流
in = new FileInputStream(filePath);
int len = 0;
//创建数据缓冲区
byte[] buffer = new byte[1024];
//通过response对象获取outputStream流
out = OutputStream();
/
connect下载
/将FileInputStream流写⼊到buffer缓冲区
while((len = in.read(buffer)) > 0) {
//使⽤OutputStream将缓冲区的数据输出到浏览器
out.write(buffer,0,len);
}
//这⼀步⾛完,将⽂件传⼊OutputStream中后,页⾯就会弹出下载框
} catch (Exception e) {
<(e.getMessage(), e);
return false;
} finally {
try {
if (out != null)
out.close();
if(in!=null)
in.close();
} catch (IOException e) {
<(e.getMessage(), e);
}
}
return true;
}else {
<("不⽀持的下载类型!");
return false;
}
}
实现效果
1.⽕狐浏览器效果
2.chrome效果,⾃动下载
补充知识:⽂件上传/下载的⼏种写法(java后端)
⽂件上传
1、框架已经帮你获取到⽂件对象File了
public boolean uploadFileToLocale(File uploadFile,String filePath) {    boolean ret_bl = false;
try {
InputStream in = new FileInputStream(uploadFile);
ret_bl=copyFile(in,filePath);
} catch (Exception e) {
e.printStackTrace();
}
return ret_bl;
}
public boolean copyFile(InputStream in,String filePath) {
boolean ret_bl = false;
FileOutputStream os=null;
try {
os = new FileOutputStream(filePath,false);
byte[] b = new byte[8 * 1024];
int length = 0;
while ((length = in.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
in.close();
ret_bl = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(os!=null){
os.close();
}
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret_bl;
}
}
2、天了个撸,SB架构师根本就飘在天空没下来,根本就没想⽂件上传这⼀回事
public String uploadByHttp(HttpServletRequest request) throws Exception{
String filePath=null;
List<String> fileNames = new ArrayList<>();
//创建⼀个通⽤的多部分解析器
CommonsMultipartResolver multipartResolver = new Session().getServletContext());
//判断 request 是否有⽂件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest =solveMultipart(request);
MultiValueMap<String,MultipartFile> multiFileMap = MultiFileMap();
List<MultipartFile> fileSet = new LinkedList<>();
for(Entry<String, List<MultipartFile>> temp : Set()){
fileSet = Value();
}
String Property("user.dir");
for(MultipartFile temp : fileSet){
filePath=rootPath+"/tem/"+OriginalFilename();
File file = new File(filePath);
if(!ists()){
file.mkdirs();
}
fileNames.OriginalFilename());
}
}
}
3、神啊,我正在撸框架,请问HttpServletRequest怎么获取
(1)在l中配置⼀个监听
<listener>
<listener-class>
org.t.request.RequestContextListener
</listener-class>
</listener>
(2)HttpServletRequest request = ((RequestAttributes()).getRequest();⽂件下载(直接⽤链接下载的不算),这⽐较简单
1、本地⽂件下载(即⽂件保存在本地)
public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {
response.setCharacterEncoding("UTF-8");
//设置ContentType字段值
response.setContentType("text/html;charset=utf-8");
//通知浏览器以下载的⽅式打开
response.addHeader("Content-type", "appllication/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
//通知⽂件流读取⽂件
InputStream in = ServletContext().getResourceAsStream(filePath);
//获取response对象的输出流
OutputStream out = OutputStream();
byte[] buffer = new byte[1024];
int len;
//循环取出流中的数据
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
}
2、远程⽂件下载(即⽹上资源下载,只知道⽂件URI)
public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){
try {
placeAll("\\\\", "/");
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)");
/
/得到输⼊流
InputStream inputStream = InputStream();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + new Bytes("GBK"),"ISO8859_1"));
//获取响应报⽂输出流对象
//获取response对象的输出流
OutputStream out = OutputStream();
byte[] buffer = new byte[1024];
int len;
//循环取出流中的数据
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
以上这篇Java后台Controller实现⽂件下载操作就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。