文件下载源码,大家看下是否正确
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;
}
}
该代码在第一次下载时会报错,再次点击又能正常下载,这是什么原因?