大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Java技巧 > struts2文件上传下载

struts2文件上传下载(1)

关键词:struts文件上传文件下载  阅读(1017) 赞(20)

[摘要]本文是对struts2文件上传下载的讲解,对学习Java编程技术有所帮助,与大家分享。

之前没写过struts2上传下载,只是知道大概怎么搞,最近项目中用到,正巧赶上了,编码过程中遇到过一些问题,如上传文件类型,中文乱码,兼容性问题等,不过都一一解决了,下面附上自己的代码。以便将来查阅...

也希望这篇随便能够帮助很多朋友少走些弯路把!

1.文件上传

首先是jsp页面的代码

在jsp页面中定义一个上传标签

 <tr>
      <td align="right" bgcolor="#F5F8F9"><b>附件:</b></td>
      <td bgcolor="#FFFFFF">
      <input type="file" name="upload" />
      </td>
      <td bgcolor="#FFFFFF">&nbsp;</td>
 </tr>

然后是BaseAction中定义的相关属性其它的就省略了(也可定义在自己的Action,换下访问修饰符即可)

 /**
 *Action基类
 **/
 public class BaseAction extends ActionSupport {
 
     protected List<File> upload;
     protected List<String> uploadContentType; //文件类型
     protected List<String> uploadFileName;    //文件名
     protected String savePath;                //保存路径
 
 }

然后是Action中的一个上传方法,代码如下:

   /**
 * 8.上传附件
   * @param upload
   */
   public void uploadAccess(List<File> upload){
         try {
             if (null != upload) {
                 for (int i = 0; i < upload.size(); i++) {
                     String path = getSavePath() + "\\"+ getUploadFileName().get(i);
                     System.out.println(path);
                     item.setAccessory(getUploadFileName().get(i));
                     
                     FileOutputStream fos = new FileOutputStream(path);
                     FileInputStream fis = new FileInputStream(getUpload().get(i));
                     byte[] buffer = new byte[1024];
                     int len = 0;
                     while ((len = fis.read(buffer)) > 0) {
                         fos.write(buffer, 0, len);
                     }
                     fis.close();
                     fos.close();
                 }
             }
         } catch (Exception e) {
             logger.error("上传附件错误。", e);
         }
     }

接着是我的struts2.xml文件

 <action name="itemRDAction_*"  method="{1}">
      <param name="savePath">e:\upload</param>
      <interceptor-ref name="defaultStack">
            <param name="fileUpload.allowedTypes">
                application/octet-stream,image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel
            </param>
            <param name="fileUpload.maximumSize">8000000</param>
      </interceptor-ref>
      <result name="show_item_rd_upd">  /WEB-INF/jsp/page_item/updItem_rd.jsp</result>
      <result name="show_item_rd_list"> /WEB-INF/jsp/page_item/listItem_rd.jsp</result>
      <result name="show_item_rd_push"> /WEB-INF/jsp/page_item/pushItem_rd.jsp</result>
 </action>

savePath为保存路径,fileUpload.allowedTypes用来限制上传文件类型 fileUpload.maximumSize 文件大小限制

2.文件下载

首先是页面中的下载链接

 <tr>
    <td width="20%" align="right" bgcolor="#F5F8F9"><b>附件:</b></td>
    <td width="40%" bgcolor="#FFFFFF">
    <div style="width:355px; float: left;">${item.accessory}</div>
        <c:if test="${!empty item.accessory}">
            <div  style="float: left;"><a style="color: black; text-decoration: none;" href="download.action?filename=${item.accessory}">下载</a></div>
        </c:if>
    </td>
    <td width="40%" bgcolor="#FFFFFF">&nbsp;</td>
 </tr> 

接着是DownloadAction的代码:

 /**
  * DownloadAction
  * 
  * @author zhaoxz
  * 
  */
 @Controller("downloadAction")
 @Scope("prototype")
 public class DownloadAction extends BaseAction {
 
     /**
      * 
      */
     private static final long serialVersionUID = -4278687717124480968L;
 
     private static Logger logger = Logger.getLogger(DownloadAction.class);
 
     private String filename;
     private InputStream inputStream;
     private String savePath;
     private String mimeType;
 
     public InputStream getInputStream() {
         try {
             String path = getSavePath() + "//"+ new String(filename.getBytes("ISO8859-1"), "utf-8");
             System.out.println(path);
             mimeType = ServletActionContext.getServletContext().getMimeType(path)+ ";charset=UTF-8";
             inputStream = new FileInputStream(path);
             String agent = request.getHeader("USER-AGENT");
             System.out.println(agent);
             if (null != agent) {
                 if (-1 != agent.indexOf("Firefox")) {// Firefox
                     mimeType = mimeType.replace("UTF-8", "ISO8859-1");
                 } else {// IE7+ Chrome
                     System.out.println("IE,Chrome");
                     filename = new String(filename.getBytes("ISO8859-1"),"utf-8");
                     filename = java.net.URLEncoder.encode(filename, "UTF-8");
                 }
             }
         } catch (Exception e) {
             logger.error("下载文件信息出错。", e);
         }
         if (null == inputStream) {
             System.out.println("getResource error");
         }
         return inputStream;
     }
 
     public void setInputStream(InputStream inputStream) {
         this.inputStream = inputStream;
     }
 
     @Override
     public String execute() throws Exception {
         return SUCCESS;
     }
 
     /*************************** get set ******************************/
     public String getSavePath() {
         return this.savePath;
     }
 
     public void setSavePath(String savePath) {
         this.savePath = savePath;
     }
 
     public String getFilename() {
         return filename;
     }
 
     public void setFilename(String filename) {
         this.filename = filename;
     }
 }
«上一页12下一页»


相关评论