java 服务器下载文件_Java实现从服务器下载文件到本地的工具类

该代码段展示了如何使用Java Servlet处理文件下载。通过设置HTTP响应头信息,包括Content-Disposition来指定文件名,并根据文件类型设置Content-Type,确保在不同浏览器中正确显示。此外,还处理了文件内容的读取和输出,以及异常处理。
摘要由CSDN通过智能技术生成

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;import java.io.*;importjava.net.URLEncoder;/***

* 将文件内容响应到浏览器*/

public classDownloadUtil {//字符编码格式

private static String charsetCode = "utf-8";/*** 文件的内容类型*/

private staticString getFileContentType(String name){

String result= "";

String fileType=name.toLowerCase();if (fileType.endsWith(".png")) {

result= "image/png";

}else if (fileType.endsWith(".gif")) {

result= "image/gif";

}else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {

result= "image/jpeg";

}else if(fileType.endsWith(".svg")){

result= "image/svg+xml";

}else if (fileType.endsWith(".doc")) {

result= "application/msword";

}else if (fileType.endsWith(".xls")) {

result= "application/x-excel";

}else if (fileType.endsWith(".zip")) {

result= "application/zip";

}else if (fileType.endsWith(".pdf")) {

result= "application/pdf";

}else{

result= "application/octet-stream";

}returnresult;

}/*** 下载文件

*@parampath 文件的位置

*@paramfileName 自定义下载文件的名称

*@paramresp http响应

*@paramreq http请求*/

public static voiddownloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){try{

File file= newFile(path);/*** 中文乱码解决*/String type= req.getHeader("User-Agent").toLowerCase();if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){/*** 谷歌或火狐*/fileName= new String(fileName.getBytes(charsetCode), "iso8859-1");

}else{/*** IE*/fileName=URLEncoder.encode(fileName, charsetCode);

}//设置响应的头部信息

resp.setHeader("content-disposition", "attachment;filename=" +fileName);//设置响应内容的类型

resp.setContentType(getFileContentType(fileName)+"; charset=" +charsetCode);//设置响应内容的长度

resp.setContentLength((int) file.length());//输出

outStream(newFileInputStream(file), resp.getOutputStream());

}catch(Exception e) {

System.out.println("执行downloadFile发生了异常:" +e.getMessage());

}

}/*** 基础字节数组输出*/

private static voidoutStream(InputStream is, OutputStream os) {try{byte[] buffer = new byte[10240];int length = -1;while ((length = is.read(buffer)) != -1) {

os.write(buffer,0, length);

os.flush();

}

}catch(Exception e) {

System.out.println("执行 outStream 发生了异常:" +e.getMessage());

}finally{try{

os.close();

}catch(IOException e) {

}try{

is.close();

}catch(IOException e) {

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值