文件上传

第一次写这个东西,以前不会!在网上搜了很多,试试也都能实现,自己这几天工作需要,有重新写了一份!

    先附上截图

没有什么其他的功能,就只有一个文件上传

以下是代码实现:

首先说说需要更改和添加的文件,需要添加的文件有(在我的程式中):upload.jsp,upload.js和一个java文件UploadFileAction.java;需要更改的文件只有一个:struts-com.xml。还有要说的是需要引入一些插件和jar包,后面会说的,先看看代码:

    文件名upload.jsp

    说明一下,这只是我从自己的工程中剪下来的,可能有多余引入文件。文件的核心内容只有红色标注的部分,其余的都可以根据自己的需要适当的删减。最后一行蓝色标注的js文件是一定要引入的!这是ajax的fileupload的插件包!自己感觉还需要引入一个json2.min.js,自己为了省事,就直接引了,反正多了也无所谓!对了,还有jquery的常用插件,我只引了jquery.min.js,这些js文件我都封装在了一个文件中了,<%@ include file="/page/comPage/comJS.html"%>,基本就这些了吧!

    代码:

 1 <head>
 2   <base href="<%=basePath%>">
 3   <title>My JSP 'sample.jsp' starting page</title>
 4   <meta http-equiv="pragma" content="no-cache">
 5   <meta http-equiv="cache-control" content="no-cache">
 6   <meta http-equiv="expires" content="0">
 7   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 8   <meta http-equiv="description" content="This is my page">
 9   <%@ include file="/page/comPage/comCSS.html"%>
10   <%@ include file="/page/comPage/navBar.html"%>
11   <link rel="stylesheet" media="screen" href="css/sample.css">
12  </head>
13  <body>
14   <div>
15    <input type="file" name="upload" id="uploadTab1" />
16    <br />
17    <input type="submit" value="上传" id="uploadTab1Btn" />
18   </div>
19  </body>
20  <%@ include file="/page/comPage/comJS.html"%>
21  <script type="text/javascript" src="js/1000/upload.js"></script>
22  <script type="text/javascript"
23   src="lib/jquery/ajaxfileupload.js" charset="UTF-8"></script>
24 </html>

 文件upload.js

    说明:上传成功和失败的弹框自己没有写,看自己的喜好了,弹框的格式有很多种,自己觉得boostarp中的弹框很酷,由于我的这个是给别人写的,所以弹框就没有写!

    代码:

 1 /*
 2  * **************************************************************** Module Name
 3  * :sample.js Create Date :2013-08-29 Description : Operation Change Function :
 4  * DAE Initialize/Start CopyRight(c)2012,Infovision Optoelectronics (Kunshan)
 5  * Co., Ltd. ****************************************************************
 6  * Modification History : Version Modified By Modified Date Annotation NO.01
 7  * Lin.Xin 2012-03-01 Initial release
 8  * 
 9  * ****************************************************************
10  */
11 $(document).ready(function() {
12  function ajaxFileUpload(obj) {
13   var globalBean ={
14      NORMAL : "0000000" 
15    };
16    $.ajaxFileUpload({
17    url : 'entCom/upload.action',// 用于文件上传的服务器端请求地址
18    secureuri : false,// 一般设置为false
19    fileElementId : obj,// 文件上传空间的id属性 <input type="file" id="upload"
20    // name="upload" />
21    dataType : 'json',// 返回值类型 一般设置为json
22    success : function(data, status) // 服务器成功响应处理函数
23    {
24     if(data.return_code ==globalBean.NORMAL){
25      //弹框显示文件上传成功
26      /*$("#uploadTab1Btn").showSuccessDialog({
27                             msg : "你已成功上传文件",
28                             callbackFn : function(data) {
29                                                          
30                             }
31                         });*/
32     }else{      
33      /*showErrorDialog(data.message);*/
34      //弹框显示文件上传失败
35     }      
36    }
37   })
38   return false;
39  };
40  //click事件,点击上传按钮触发
41  $("#uploadTab1Btn").click(function() {
42   var uploadFile = $.trim($("#uploadTab1").val());
43   if (uploadFile == "") {
44    showErrorDialog(PLEASE_SELECT_FILE_TAG);
45    return;
46   }
47   ajaxFileUpload("uploadTab1");
48  }); 
49 });
50  

 

 文件:UploadFileAction.java

    说明:这个是我抄的,但是可以用,上传的文件放置的路径是红色标注部分,自己可以更改!还有就是上传文件的格式我自己只卡了几个,可以再改!

    代码:

  1 package com.ivo.action.datum;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileOutputStream;
  5 import java.text.SimpleDateFormat;
  6 import java.util.Date;
  7 import javax.servlet.http.HttpServletResponse;
  8 import org.apache.log4j.Logger;
  9 import org.apache.struts2.ServletActionContext;
 10 import com.opensymphony.xwork2.ActionSupport;
 11 public class UploadFileAction extends ActionSupport {
 12  /*
 13   * private File upload; private String
 14   * uploadFileName;//struts2的拦截器FileUploadInterceptor根据请求对象中参数
 15   * "fileInput"来自行生产的一个固有属性
 16   * 
 17   * public File getUpload() { return upload; }
 18   * 
 19   * public void setUpload(File upload) { this.upload = upload; }
 20   * 
 21   * public String getUploadFileName() { return uploadFileName; }
 22   * 
 23   * public void setUploadFileName(String uploadFileName) {
 24   * this.uploadFileName = uploadFileName; }
 25   */
 26  //private Logger logger = Logger.getLogger(AdjustAction.class);
 27  private File upload;
 28  private String uploadContentType;
 29  private String uploadFileName;
 30  private String message = "你已成功上传文件";
 31  private String return_code;
 32  String NORMAL = "0000000";
 33  
 34  public File getUpload() {
 35   return upload;
 36  }
 37  public void setUpload(File upload) {
 38   this.upload = upload;
 39  }
 40  public String getUploadContentType() {
 41   return uploadContentType;
 42  }
 43  public void setUploadContentType(String uploadContentType) {
 44   this.uploadContentType = uploadContentType;
 45  }
 46  public String getUploadFileName() {
 47   return uploadFileName;
 48  }
 49  public void setUploadFileName(String uploadFileName) {
 50   this.uploadFileName = uploadFileName;
 51  }
 52  public String getMessage() {
 53   return message;
 54  }
 55  public void setMessage(String message) {
 56   this.message = message;
 57  }
 58     public String getReturn_code() {
 59   return return_code;
 60  }
 61  public void setReturn_code(String return_code) {
 62   this.return_code = return_code;
 63  }  
 64  
 65  @SuppressWarnings("deprecation")
 66  public String uploadFile() throws Exception {
 67   /*
 68    * String savePath = ServletActionContext.getRequest().getRealPath("");
 69    * System.out.println("Path:"+savePath); FileOutputStream fos = new
 70    * FileOutputStream(savePath+"()); FileInputStream
 71    * fis = new FileInputStream(getUpload()); byte[] buffer = new
 72    * byte[1024]; int len = 0; while((len = fis.read(buffer))>0) {
 73    * fos.write(buffer,0,len); } return SUCCESS;
 74    */
 75   // String savePath = ServletActionContext.getRequest().getRealPath("");
 76   String savePath = "D:\\qra\\fileUpload";// 存放上传文件的路径名
 77   String extName = "";
 78   String newFileName = "";
 79   System.out.println("原文件名:" + getUploadFileName());
 80   System.out.println("路径:" + savePath);
 81   // 获取扩展名
 82   String fileName = getUploadFileName();
 83   if (fileName.lastIndexOf(".") > -1) {
 84    extName = fileName.substring(fileName.lastIndexOf("."));
 85    System.out.println(extName);
 86   }
 87   try {
 88    if (fileName.endsWith(".exe")) {
 89     message = "对不起,你上传的文件格式不允许!";
 90     return SUCCESS;
 91    }
 92    FileOutputStream fos = new FileOutputStream(savePath + "\\"
 93      + getUploadFileName());
 94    FileInputStream fis = new FileInputStream(getUpload());
 95    byte[] buffer = new byte[1024];
 96    int len = 0;
 97    while ((len = fis.read(buffer)) > 0) {
 98     fos.write(buffer, 0, len);
 99    }
100    fis.close();
101    fos.flush();
102    return_code = NORMAL;
103   } catch (Exception e) {
104    //logger.error(e.getMessage());
105    message = "对不起,上传失败了!";
106   }
107   /*
108    * String nowTime = new SimpleDateFormat("yyyyMMDDHHmmssSSS").format(new
109    * Date()); newFileName = nowTime+extName;
110    * System.out.println("保存的文件名称:"+savePath+newFileName);
111    * upload.renameTo(new File(savePath+newFileName)); HttpServletResponse
112    * response = ServletActionContext.getResponse();
113    * response.setCharacterEncoding("utf-8");
114    * response.getWriter().print("成功上传文件《"+fileName+"》!");
115    */ 
116   return SUCCESS;
117  }
118 }

更改的文件:struts-com.xml

说明:这段代码可以写在struts.xml中,如果要像我这样写,而且没有这个文件就需要新建了,在struts.xml中调一下这个文件就可以了,调用的代码是:<include file="/com/struts/struts-com.xml" />路径根据自己的需要更改!

添加的代码:

 1 <package name="enter" extends="json-default" namespace="/entCom">
 2   
 3   <action name="upload" class="com.ivo.action.datum.UploadFileAction"
 4    method="uploadFile">
 5    <result type="json" name="success">
 6     <param name="contentType">
 7      text/html
 8                 </param>
 9    </result>
10    <result type="json" name="error">
11     <param name="contentType">
12      text/html
13                 </param>
14    </result>
15   </action>
16 </package>

最后说说文件上传的这个流程吧!在前台界面点击“上传”按钮,触发js文件中的click事件,再根据js文件中的url : 'entCom/upload.action'这句话去xml中找后台对应的action,也就是那个java文件,在xml文件中告诉程式该去找的路径:<action name="upload" class="com.ivo.action.datum.UploadFileAction",在java文件中创建文件上传的输入输出!基本上就这些了,我自己是一菜鸟,也只能理解这么多!

 

 

 

 

 

posted @ 2014-03-24 15:09  暖暖的拥抱  阅读(217)  评论(0编辑  收藏  举报