Java实现从服务器下载⽂件到本地的⼯具类话不多说,直接上代码......
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.URLEncoder;
/***
* 将⽂件内容响应到浏览器
*/
public class DownloadUtil {
// 字符编码格式
private static String charsetCode = "utf-8";
/
**
* ⽂件的内容类型
*/
private static String getFileContentType(String name){
String result = "";
String fileType = LowerCase();
if (dsWith(".png")) {
result = "image/png";
} else if (dsWith(".gif")) {
result = "image/gif";
} else if (dsWith(".jpg") || dsWith(".jpeg")) {
result = "image/jpeg";
} else dsWith(".svg")){
result = "image/svg+xml";
}else if (dsWith(".doc")) {
result = "application/msword";
} else if (dsWith(".xls")) {
result = "application/x-excel";
} else if (dsWith(".zip")) {
result = "application/zip";
} else if (dsWith(".pdf")) {
result = "application/pdf";
} else {
result = "application/octet-stream";
}
return result;
}
/**
* 下载⽂件
* @param path ⽂件的位置
* @param fileName ⾃定义下载⽂件的名称
* @param resp http响应
* @param req http请求
*/
public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){
try {
File file = new File(path);
/**
* 中⽂乱码解决
*/
String type = Header("User-Agent").toLowerCase();
if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){
/**
* ⾕歌或⽕狐
*/
fileName = new Bytes(charsetCode), "iso8859-1");
chrome直接下载}else{
/**
* IE
*/
fileName = de(fileName, charsetCode);
}
// 设置响应的头部信息
resp.setHeader("content-disposition", "attachment;filename=" + fileName);
// 设置响应内容的类型
resp.setContentType(getFileContentType(fileName)+"; charset=" + charsetCode);
// 设置响应内容的长度
resp.setContentLength((int) file.length());
// 输出
outStream(new FileInputStream(file), OutputStream());
} catch (Exception e) {
System.out.println("执⾏downloadFile发⽣了异常:" + e.getMessage());
}
}
/**
* 基础字节数组输出
*/
private static void outStream(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) {
}
}
}
}
使⽤。。( springboot项⽬ )
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论