文件下载

本文介绍了一个用于Java Web应用的文件下载工具类实现。该工具类能够处理文件路径,支持中文文件名,并通过HTTP响应将文件返回给客户端。文章详细展示了如何读取文件并将其输出到用户的浏览器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package com.prs.framework.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class FileDownloadUtil {

private FileDownloadUtil() {

}

/**
* 下载文件
* @param filePath --文件完整路径
* @param response --HttpServletResponse对象
*/
public static void downloadFile(String filePath, HttpServletResponse response) {

String fileName = ""; // 文件名,输出到用户的下载对话框
// 从文件完整路径中提取文件名,并进行编码转换,防止不能正确显示中文名
try {
if (filePath.lastIndexOf("/") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length()).getBytes("GB2312"), "ISO8859_1");
} else if (filePath.lastIndexOf("\\") > 0) {
fileName = new String(filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.length()).getBytes("GB2312"), "ISO8859_1");
}
} catch (Exception e) {
e.printStackTrace();
}
// 打开指定文件的流信息
FileInputStream fs = null;
try {
fs = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// 设置响应头和保存文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 写出流信息
int b = 0;
try {
PrintWriter out = response.getWriter();
while ((b = fs.read()) != -1) {
out.write(b);
}
fs.close();
out.close();
System.out.println("文件下载完毕.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载文件失败!");
}
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值