文件下载源码,大家看下是否正确

soarsoar77 2012-10-09 08:44:34
public class DownFileAction extends Action{
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

Collection<ERRBean> colerr = new ArrayList<ERRBean>();

request.setCharacterEncoding("GB2312");

String filename = request.getParameter("fname");
System.out.print("filename:" + filename);
//从配置文件中读取格式文件路径
Configuration config1 = new Configuration("config/fkll.properties");
String SystemType = config1.getValue("SysType");
String fPath =null;
if (SystemType.equals("1"))
{
fPath = config1.getValue("FileC1");
}

if (SystemType.equals("2"))
{
fPath = config1.getValue("FileC2");
}

if (SystemType.equals("3"))
{
fPath = config1.getValue("FileC3");
}
String filepathname =fPath + filename.trim();
System.out.print("filepathname:" + filepathname);

File f =new File(filepathname);
if (!f.exists())
{
ERRBean tmpErr = new ERRBean();
tmpErr.setErrNR("文件不存在,无法下载!");
tmpErr.setErrPage("main_FileList.jsp");
tmpErr.setErrBZ("错误");
colerr.add(tmpErr);
request.getSession().setAttribute("colerr", colerr);
return mapping.findForward("failure");
}

byte[] b = null;


try {
String snm_path;

snm_path = filepathname;
FileInputStream aa = new FileInputStream(snm_path);
b = new byte[aa.available()];
aa.read(b);
aa.close();
// 将文件信息取回到页面中
response.setContentType("application/x-msdownload;charset=GBK");
String s = " attachment;filename=" + new String(filename.getBytes("GBK"), "ISO8859_1"); //
response.setHeader("Content-Disposition", s); // 以上输出文件元信息
response.setContentLength(b.length);
response.getOutputStream().write(b, 0, b.length);
response.getOutputStream().close();

} catch (IOException e) {
System.out.println("下载文件失败: " + e.getMessage());
}
return null;
}
}

该代码在第一次下载时会报错,再次点击又能正常下载,这是什么原因?
...全文
84 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
BJ_黑夜 2012-10-09
  • 打赏
  • 举报
回复
发错地方了 亲

58,441

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧