vjame

优化代码是无止境的
随笔 - 65, 文章 - 9, 评论 - 26, 引用 - 0
数据加载中……

使用FormFile处理文件上传下载

1.首先界面设计,自己搞定 .。。。



2. 然后在jsp页面中定义文件上传标签,name 要和From中定义的FormFile变量名称一致



3. 在Form中定义FormFile私有变量, 它和文件上传标签名称要一样。



4.  ,这里要先在po类里面定义个字节变量content 接收上传来的文件内容


5. 在Action的增加方法中,首先判断页面上是否有文件被上传,然后把内容设置到po类里面去 ,这里getFileData()得到的是字节.

6. 文件需要提交下载时,在Action中加入一下代码

    //下载公文附件
    public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        DocumentActionForm daf 
= (DocumentActionForm)form;
        
        Document document 
= documentManager.findDocument(daf.getId());
        
        response.reset();
        response.setContentType(
"application/x-download;charset=GBK");
        response.setHeader(
"Content-Disposition""attachment;filename=temp.doc");
        
        response.getOutputStream().write(document.getContent());
        
        response.getOutputStream().flush();
        response.getOutputStream().close();
        
        
//指示struts,不要对返回值进行处理
        return null;
    }

7. 程序运行效果
另外一种方法在Action中添加download方法也是可以达到下载功能的目的
    public ActionForward downloadFile(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception{

        String docId 
= request.getParameter("docId");
        Doc doc 
= baseService.find(docId);
        SerializableBlob serBlob 
= null;
        
if(doc!= null){
            serBlob 
= (SerializableBlob) doc.getContentBinary();
        }

        Blob blob 
= serBlob.getWrappedBlob();
        
try {
            
if (blob != null) {
                response.reset();
                BufferedInputStream in 
= new BufferedInputStream(
                        blob.getBinaryStream()); 
// 输入流
                response.setContentType("bin:charset=utf-8");
                response.setHeader(
                                
"Content-Disposition",
                                
"attachment; filename=temp.doc"); // 设置保存页面提示信息
                byte[] b = new byte[100];
                
int len;
                
while ((len = in.read(b)) > 0) {
                    response.getOutputStream().write(b, 
0, len);
                }
                in.close();
            }
        } 
catch (Exception e) {
            
return null;
        }
        
return null;
    }

posted on 2008-11-07 01:24 lanjh 阅读(2985) 评论(0)  编辑  收藏 所属分类: Java Web


只有注册用户登录后才能发表评论。


网站导航: