下载文件如word,pdf文件等

本文提供了一个使用Java实现的从服务器下载指定PDF文件的方法。该方法通过读取服务器上特定路径下的PDF文件,并将其发送到客户端以供下载。具体步骤包括获取文件的实际路径、设置HTTP响应头以便浏览器识别为文件下载、读取文件内容并输出到客户端。

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

/**
* 下载pdf
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward downnewYearPdf(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
byte[] buffer;
InputStream ins;
String dirPaths, filepath;
try {
// 工程类路径,用来获取保存文件的的路径
String url = request.getSession().getServletContext().getRealPath(request.getRequestURI());
int a = url.lastIndexOf(File.separator);
url = url.substring(0, a);
String name = "newyear.pdf";//文件名字
filepath = "/newyear/newYear.pdf";//文件根目录下的路径
dirPaths = url + filepath;//总路径
try {
// 读取文件
if (!"".equals(dirPaths)) {
ins = new FileInputStream(dirPaths);
int bytesRead = 0;
buffer = new byte[4096];
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;"
+ " filename="
+ new String(name.getBytes(), "ISO-8859-1"));
while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {
try {
response.getOutputStream().write(buffer);
response.getOutputStream().flush();
} catch (Exception ex) {
throw new Exception("读数据流出现错误");
}
}
buffer = null;
response.getOutputStream();
ins.close();
}
} catch (Exception ex) {
request.setAttribute(Constants.C_ERROR_MSG, "“" + name
+ "文件不存在硬盘中“");
return mapping.findForward("error");
}

} catch (Exception ex) {
request.setAttribute(Constants.C_ERROR_MSG, "文件下载出现错误");
return mapping.findForward("error");
}
return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值