溫馨提示:您的每一次轉載,體現了我寫此文的意義!!!煩請您在轉載時注明出處http://www.aygfsteel.com/sxyx2008/謝謝合作!!!

          雪山飛鵠

          溫馨提示:您的每一次轉載,體現了我寫此文的意義!!!煩請您在轉載時注明出處http://www.aygfsteel.com/sxyx2008/謝謝合作!!!

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            215 Posts :: 1 Stories :: 674 Comments :: 0 Trackbacks

          點我下載工程代碼
          由于項目需求,在處理文件上傳時需要使用到文件的異步上傳。這里使用Jquery Ajax File Uploader這個組件下載地址http://www.phpletter.com/download_project_version.php?version_id=6
          服務器端采用struts2來處理文件上傳。
          所需環境:
          jquery.js
          ajaxfileupload.js
          struts2所依賴的jar包
          及struts2-json-plugin-2.1.8.1.jar
          編寫文件上傳的Action

          package com.ajaxfile.action;

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;

          import org.apache.struts2.ServletActionContext;

          import com.opensymphony.xwork2.ActionSupport;

          @SuppressWarnings(
          "serial")
          public class FileAction extends ActionSupport {

              
          private File file;
              
          private String fileFileName;
              
          private String fileFileContentType;

              
          private String message = "你已成功上傳文件";
              
              
          public String getMessage() {
                  
          return message;
              }

              
          public void setMessage(String message) {
                  
          this.message = message;
              }

              
          public File getFile() {
                  
          return file;
              }

              
          public void setFile(File file) {
                  
          this.file = file;
              }

              
          public String getFileFileName() {
                  
          return fileFileName;
              }

              
          public void setFileFileName(String fileFileName) {
                  
          this.fileFileName = fileFileName;
              }

              
          public String getFileFileContentType() {
                  
          return fileFileContentType;
              }

              
          public void setFileFileContentType(String fileFileContentType) {
                  
          this.fileFileContentType = fileFileContentType;
              }

              @SuppressWarnings(
          "deprecation")
              @Override
              
          public String execute() throws Exception {
                  
                  String path 
          = ServletActionContext.getRequest().getRealPath("/upload");

                  
          try {
                      File f 
          = this.getFile();
                      
          if(this.getFileFileName().endsWith(".exe")){
                          message
          ="對不起,你上傳的文件格式不允許!!!";
                          
          return ERROR;
                      }
                      FileInputStream inputStream 
          = new FileInputStream(f);
                      FileOutputStream outputStream 
          = new FileOutputStream(path + "/"+ this.getFileFileName());
                      
          byte[] buf = new byte[1024];
                      
          int length = 0;
                      
          while ((length = inputStream.read(buf)) != -1) {
                          outputStream.write(buf, 
          0, length);
                      }
                      inputStream.close();
                      outputStream.flush();
                  } 
          catch (Exception e) {
                      e.printStackTrace();
                      message 
          = "對不起,文件上傳失敗了!!!!";
                  }
                  
          return SUCCESS;
              }

          }
          struts.xml
          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
          <struts>
              
          <package name="struts2" extends="json-default">
                  
          <action name="fileUploadAction" class="com.ajaxfile.action.FileAction">
                      
          <result type="json" name="success">
                          
          <param name="contentType">
                              text/html
                          
          </param>
                      
          </result>
                      
          <result type="json" name="error">
                          
          <param name="contentType">
                              text/html
                          
          </param>
                      
          </result>
                  
          </action>
              
          </package>
          </struts>    
          注意結合Action觀察struts.xml中result的配置。 

          contentType參數是一定要有的,否則瀏覽器總是提示將返回的JSON結果另存為文件,不會交給ajaxfileupload處理。這是因為struts2 JSON Plugin默認的contentType為application/json,而ajaxfileupload則要求為text/html。
          文件上傳的jsp頁面

          <%@ page language="java" contentType="text/html; charset=UTF-8"
              pageEncoding
          ="UTF-8"%>
          <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
          <html>
              
          <head>
                  
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                  
          <title>Insert title here</title>
                  
          <script type="text/javascript" src="js/jquery.js"></script>
                  
          <script type="text/javascript" src="js/ajaxfileupload.js"></script>
                  
          <script type="text/javascript">
              
          function ajaxFileUpload()
              {
                  
                  $(
          "#loading")
                  .ajaxStart(
          function(){
                      $(
          this).show();
                  })
          //開始上傳文件時顯示一個圖片
                  .ajaxComplete(function(){
                      $(
          this).hide();
                  });
          //文件上傳完成將圖片隱藏起來
                  
                  $.ajaxFileUpload
                  (
                      {
                          url:'fileUploadAction.action',
          //用于文件上傳的服務器端請求地址
                          secureuri:false,//一般設置為false
                          fileElementId:'file',//文件上傳空間的id屬性  <input type="file" id="file" name="file" />
                          dataType: 'json',//返回值類型 一般設置為json
                          success: function (data, status)  //服務器成功響應處理函數
                          {
                              alert(data.message);
          //從服務器返回的json中取出message中的數據,其中message為在struts2中action中定義的成員變量
                              
                              
          if(typeof(data.error) != 'undefined')
                              {
                                  
          if(data.error != '')
                                  {
                                      alert(data.error);
                                  }
          else
                                  {
                                      alert(data.message);
                                  }
                              }
                          },
                          error: 
          function (data, status, e)//服務器響應失敗處理函數
                          {
                              alert(e);
                          }
                      }
                  )
                  
                  
          return false;

              }
              
          </script>
              
          </head>
              
          <body>
                  
          <img src="loading.gif" id="loading" style="display: none;">
                  
          <input type="file" id="file" name="file" />
                  
          <br />
                  
          <input type="button" value="上傳" onclick="return ajaxFileUpload();">
              
          </body>
          </html>

           注意觀察<body>中的代碼,并沒有form表單。只是在按鈕點擊的時候觸發ajaxFileUpload()方法。需要注意的是js文件引入的先后順序,ajaxfileupload.js依賴于jquery因此你知道的。
          點我下載工程代碼

          posted on 2010-11-02 16:57 雪山飛鵠 閱讀(60649) 評論(11)  編輯  收藏 所屬分類: struts2 、js

          Feedback

          # re: jquery之ajaxfileupload異步上傳插件 2012-04-17 20:08 藍水域
          謝謝  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2013-03-20 11:08 文秀
          非常感謝  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2013-03-23 14:03 so_fast
          非常感謝!  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件[未登錄] 2013-03-28 13:55 kevin
          非常感謝,真的可以用  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2013-05-10 17:06 zwq
          如果我想發送文件
          同時在發送一些字符串到服務器,該怎么實現呢
          我現在能把文件發到服務器端了  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件[未登錄] 2013-06-20 16:02
          真的很感激你啊,樓主好人??!今天找了很多資料,一直糾結到底應該使用什么框架來完成自己的ajax應用??吹綐侵鞯奈恼挛一砣婚_朗,決定使用jq。之前用過jq,感覺比較容易上手。  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2013-09-03 12:08 fsadf
          fdfaffaf  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2013-09-06 15:49 華仔
          請問一個問題啊,使用這個AjaxFileUpload.js 這個插件為什么會用到jquery ajax 全局事件啦 按理說它是一個form提交 根本就使用不到 ajax 全局事件啊 但是使用這種jQuery.event.trigger 事件的方式 。 這是為什么啊 ??? from 表達提交為什么會使用到 ajax 事件的全局事件。  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2014-04-27 15:31 shengyang
          thank you very much  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2014-08-02 23:05 qym19920
          用這個組件上傳的文件都是修改了文件的名字,怎么才能獲取上傳文件原來的名字,并且保存在服務端時,名字不更改,我在FileLoadServelt中改了一下代碼,但是沒有獲取到原來文件的名字。。。。還請哪位知道的說一下  回復  更多評論
            

          # re: jquery之ajaxfileupload異步上傳插件 2016-02-16 17:02 小蔣
          為什么我點擊“上傳”按鈕沒有作用?  回復  更多評論
            

          主站蜘蛛池模板: 芦溪县| 南阳市| 股票| 通辽市| 襄城县| 东阿县| 阿巴嘎旗| 榆中县| 安徽省| 满洲里市| 淳安县| 湄潭县| 贵港市| 兴宁市| 越西县| 巨鹿县| 名山县| 富顺县| 乐山市| 巩义市| 安福县| 普格县| 布拖县| 桐乡市| 新沂市| 蓝山县| 沙河市| 闽清县| 班玛县| 马龙县| 衢州市| 交口县| 彩票| 许昌县| 桑植县| 安阳县| 长垣县| 南溪县| 阿勒泰市| 泸州市| 紫阳县|