Java Web实现 使用浏览器从服务器下载文件。
代码实现:
package com.juneyaoair.util;
import lombok.SneakyThrows;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
public class FileUtile {
/**文件下载并且浏览器导出**/
@SneakyThrows
public static void downloadFile(String file, String fileName, HttpServletResponse
response, HttpServletRequest request) {
OutputStream out = null;
FileInputStream in = null;
try {
// 1.读取要下载的内容
in = new FileInputStream(new File(file));
// 2. 告诉浏览器下载的方式以及一些设置
// 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
String agent = request.getHeader("user-agent");
if (agent.contains("FireFox")) {
fileName = new String(file.getBytes("UTF-8"), "iso-8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
// 设置下载文件的mineType,告诉浏览器下载文件类型
String mineType = request.getServletContext().getMimeType(fileName);
response.setContentType(mineType);
// 设置一个响应头,无论是否被浏览器解析,都下载
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
// 将要下载的文件内容通过输出流写到浏览器
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
deleteFile(file);
} catch (
IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
/**
* 删除单个文件
*
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
/**检查导出文件**/
public String examineExportFile(String title, String[] header,
List<FlightActivityVo> list) throws IOException {
String pathString = this.getPathString();
String pathName = pathString + File.separator + title;
log.info("*******************************pathName==================>" +
pathName);
File file = new File(pathName);
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);
for (FlightActivityVo flightActivityVo : list) {
csvPrinter.printRecord(flightActivityVo.getOrigination(),
flightActivityVo.getDestination(),flightActivityVo.getSegmentDisNumber(),
flightActivityVo.getSegmentNumber(), flightActivityVo.getIntegralNumber(),
flightActivityVo.getIntegralMax());
}
csvPrinter.flush();
csvPrinter.close();
log.info("导出文件创建成功");
return pathName;
}
/**获取文件路径**/
public static String getPathString() {
String path = PathUtil.getRootPath();
File file = new File(path);
File parentFile = file.getParentFile().getParentFile().getParentFile();
String pathString = "";
if (parentFile.toString().startsWith("file:")) {
pathString = parentFile.toString().substring(5,
parentFile.toString().length());
} else {
pathString = parentFile.toString();
}
log.info("*******************************pathString==================>" +
pathString);
return pathString;
}
/**文件压缩**/
public static String zipCsv(String fileName) {
//定义zip压缩包
ZipOutputStream zos = null;
InputStream fis = null;
String pathString = getPathString();
String result = "";
try {
String zipName = "数据导出" + System.currentTimeMillis() + ".zip";
zos = new ZipOutputStream(new FileOutputStream(pathString + zipName));
fis = new FileInputStream(new String((pathString + File.separator +
fileName).getBytes(StandardCharsets.UTF_8),StandardCharsets.UTF_8));
ZipEntry z1 = new ZipEntry(fileName);
zos.putNextEntry(z1);
byte[] b = new byte[1024];
int leng = 0;
while ((leng = fis.read(b)) != -1) {
zos.write(b, 0, leng);
}
fis.close();
zos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return zipName;
}
}