我做了个struts2的文件下载功能,有问题,请大神帮忙解决
补充:我在前台给文件一个id,单击事件通过ajax请求对应的下载文件action
在action中定义3个变量fileName ,filePath,id,getter和setter方法
在getDownFile(){
Attachment att = attService.getAttachment(id);//调用service层的方法,查询出对应的id
this.fileName = att.getFileName();//获取文件名
this.filePath = att.getFilePath();//获取路径
File fdesc = new File(filePath +fileName);
InputStream is = new FileInputStream (fdesc);
return is;
}
fileName 和filePath 是确定可以取到的,而且struts.xml配置文件也没有什么问题,但是下载不了,请问是什么造成的!
追问:java.lang.classcastException:java.io.FileInputStream cannot be cast to java.lang.string
这个异常,知道怎么回事吗?struts2 这些 可以再struts.xml中配置好了吧?那配置文件中还要写什么呢?
<param name="contentType">
<param name="contentDisposition">还需要在配置文件中配置吗?
那也不对啊,,。。。下载请求的action怎么知道执行这个方法呢?可否说明下struts.xml的配置,小弟感激不尽啊!
其他:应该还有一个 OutputStream吧?只有InputStream那只是读取文件流,OutputStream才是向外输出流的吧。 public void getDownFile(){
try{
Attachment att = attService.getAttachment(id);//调用service层的方法,查询出对应的id
this.fileName = att.getFileName();//获取文件名
this.filePath = att.getFilePath();//获取路径
File fdesc = new File(filePath +fileName);
HttpServletResponse response = ServletActionContext.getResponse(); //获取response对象
response.addHeader("Content- Disposition","attachment;filename=" + URLEncoder.encode("文件名称","UTF-8"));//设置文件名称
OutputStream out = new BufferedOutputStream(response.getOutputStream());//获取输出流
InputStream is = new BufferedInputStream(new FileInputStream(fdesc));//将文件读取
byte[] b = new byte[is.available()];
is.read(b);
is.close();
out.write(b);//向页面输出(即是下载)
out.close();
}catch(Exception e){
e.printStackTrace()
}
}
上一个:什么样的jar包是有源代码的?
下一个:使用java时需要单独下载editplus吗