首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Struts实现文件上载

2012-10-09 
Struts实现文件下载1.struts 1 通过struts实现文件下载有两种方式,一种是继承DownloadAction,一种是读取文

Struts实现文件下载

1.struts 1
通过struts实现文件下载有两种方式,一种是继承DownloadAction,一种是读取文件流然后output到response里面。
? 1.继承DownloadAction,需要重写getStreamInfo方法,返回StreamInfo,DownloadAction有两个StreamInfo,FileStreamInfo和ResourceStreamInfo。
? 例子:

public ActionForward download(ActionMapping mapping, ActionForm form,                HttpServletRequest request, HttpServletResponse response) {            try           {                String path = new String(rootFolder +request.getParameter("path"));                File file = new File(path);                String filename = file.getName();                                //取得文件的扩展名ext                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();                                InputStream fis = new BufferedInputStream(new FileInputStream(path));                byte[] buffer = new byte[fis.available()];                fis.read(buffer);                fis.close();                                response.reset();                response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes()));                response.addHeader("Content-Length", ""+file.length()); //设置返回的文件类型                OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); //得到向客户端输出二进制数据的对象                //根据扩展名声称客户端浏览器mime类型                if(ext.equals("DOC"))                    response.setContentType("application/msword");                else                   response.setContentType("application/octet-stream"); //设置返回的文件类型                toClient.write(buffer); //输出数据                toClient.flush();                toClient.close();                }                catch(IOException ex){                    ex.printStackTrace();                }                return null;            }   

热点排行