ITeye博客

struts的文件上传and下载

eddiegift · 2008-02-29 18:16 · struts1.x · Markdown

public ActionForward upload (ActionMapping mapping, 
                               ActionForm actionForm, 
                               HttpServletRequest request, 
                               HttpServletResponse response) { 
    FileForm fileForm = (FileForm) actionForm; 
    int count = UploadAndDown.uploadFile(fileForm); 
    if (count > 0) { 
      this.save(request); 
      return mapping.findForward("sucess"); 
    } else { 
      return mapping.getInputForward(); 
    } 
  } 

  //将可供下载的文件名列表储存在请求中,在页面中显示出来
  private void save(HttpServletRequest request) {
    try {
      Vector v = DataBaseDAO.query();
      request.getSession().setAttribute("filename",v);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public ActionForward down(ActionMapping mapping, 
                               ActionForm actionForm, 
                               HttpServletRequest request, 
                               HttpServletResponse response) { 
       try { 
         FileForm fileForm = (FileForm) actionForm; 
         InputStream file = UploadAndDown.down(fileForm.getName()); 
         byte[] bit = new byte[1024]; 
         int len = file.read(bit); 
         ServletOutputStream out = response.getOutputStream(); 

// 添加此句为下载文件,否则将文件流发送到页面<img src="actionPatch"/>中,在页面将图片显示出来 
//         response.addHeader("Content-Disposition","attachment;filename=" + "tt.jpg"); 
         while (len != -1) { 
           out.write(bit,0,len); 
           len = file.read(bit); 
         } 
         out.close(); 
         file.close(); 
       return mapping.findForward("show"); 
//         return null; 
       } catch (Exception e) { 
         e.printStackTrace(); 
         return null; 
       } 
   } 

   public static int uploadFile(FileForm fileForm) { 
    try { 
      int count = DataBaseDAO.insert(fileForm); 
      return count; 
    } catch (Exception e) { 
      e.printStackTrace(); 
      return 0; 
    } 
  } 

  public static InputStream down(String name) { 
    try { 
      // Vector v = DataBaseDAO.getFile(name); 
      //FileInputStream input = (FileInputStream)v.get(0); 
      InputStream input = new FileInputStream("F:\\picture\\13-02-07_1455.jpg"); 
      return input; 
    } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
    } 
  }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。