JunXiu

          flex Httpservice java 傳參數 上傳文件 接收參數

          上傳參數:httpservice封裝了 urlrequest
          上傳文件:所有上傳都是用POST  Content type為:multipart/form-data (如同html表單的設置一樣)

          var request:URLRequest=new URLRequest("http://localhost:8080/webproject12/servlet/upload");
          myFileRef.upload(request);

          可以加一個filter class  當提交成功時候 綁定一個變量到session
          filter過濾所有要訪問JSP生成XML的請求 如果session沒有這個變量  拒絕訪問(方式根據鏈接訪問JSP)
          提交文件用import flash.net.FileReference;

          MXML部分:

          <?xml version="1.0" encoding="utf-8"?>
          <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
          <mx:Script>
              <![CDATA[
              /**
              * 一個HttpService 與servlet通信的例子
              * 發送文件 和上傳表單  先文件上傳成功后繼續傳送表單
              * 發送文件的成功由事件監聽 
              * 發送表單后會返回由JSP生成的動態XML文件
              * */
              import mx.rpc.events.FaultEvent;
              import mx.rpc.events.ResultEvent;
              import flash.net.URLRequest;
              import flash.net.FileReference;
              import flash.events.Event;
              import flash.events.IOErrorEvent;
           
             
                  private var myFileRef:FileReference=null ;
                  private var request:URLRequest=null;
                  private function doFileBrowse():void{//點擊瀏覽文件選項
                 
                             myFileRef = new FileReference();           
                          myFileRef.addEventListener(Event.SELECT,doSelect);
                          myFileRef.browse();   
                  }
                  private function doSelect(evt:Event):void{//為文件文本框賦值
                      imageName.text=myFileRef.name.toString();
                  }
                  private function doUpForm():void{//點擊最后提交按鈕

                      request=new URLRequest("http://localhost:8080/webproject12/servlet/upload");
                      myFileRef.upload(request); //圖片文件的提交
                         myFileRef.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);//文件失敗上傳監聽事件
                      myFileRef.addEventListener(Event.COMPLETE,doFileUploadComplete);//文件成功上傳監聽事件   
                  }
                  private function errorHandler(evt:IOErrorEvent):void{
                          trace("上傳失敗,檢查網絡");
                  }
                  private function doFileUploadComplete(evt:Event):void{
                          trace("文件上傳成功 繼續傳送表單");
                          up.send();//繼續提交文字表單
                   
                  }
                 
                  private function doResult(event:ResultEvent):void{
                      trace(event.result);
                  }
                  private function doFault(event:FaultEvent):void{
                           trace("表單發送失敗");
                  }
              ]]>
          </mx:Script>

              <mx:HTTPService id="up" url="http://localhost:8080/webproject12/flextest"
                   result="doResult(event)" fault="doFault(event)"
                    method="POST" resultFormat="xml" >
                  <mx:request xmlns="">
                  <username>
                      {username.text}
                  </username>
                  <imageName>
                      {imageName.text}
                  </imageName>
                  </mx:request>
              </mx:HTTPService>
              <mx:VBox height="100%" width="100%">
                  <mx:Form>
                      <mx:FormHeading label=" test load"/>
                      <mx:FormItem label=" username:">
                          <mx:TextInput id="username"/>
                      </mx:FormItem>
                      <mx:FormItem label="Image Name" direction="horizontal">
                          <mx:TextInput id="imageName" editable="false"/>
                          <mx:Button click="doFileBrowse()" label="Browse"/>
                      </mx:FormItem>
                      <mx:FormItem>
                          <mx:Button label="提交" click="doUpForm()"/>
                      </mx:FormItem>
                  </mx:Form>
              </mx:VBox>   
          </mx:Application>

          servlet部分:
          upload。java   不需要回饋 文件接收器
          1.
          要設置好初始化參數  給與一個上傳附件的路徑
          通過:
          private ServletContext sc =config.getServletContext();
          sc.getRealPath("/");得到應用真是根目錄
          private String savePath = config.getInitParameter("savePath");// 保存文件夾

          sc.getRealPath("/")+savePath 是保存目錄

          2.
          用了COMMONS FILEUPLOAD組件 和commons IO 組件

          package org.zizi.servlet;

          import java.io.File;
          import java.io.IOException;
          import java.io.PrintWriter;
          import java.util.Iterator;
          import java.util.List;

          import javax.servlet.ServletConfig;
          import javax.servlet.ServletContext;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          import org.apache.commons.fileupload.FileItem;
          import org.apache.commons.fileupload.FileUploadException;
          import org.apache.commons.fileupload.disk.DiskFileItemFactory;
          import org.apache.commons.fileupload.servlet.ServletFileUpload;

          public class UploadServelt extends HttpServlet {

              private static final long serialVersionUID = -850828778548588525L;
              private ServletContext sc;// application 上傳組件要用
              private String savePath;// 保存路徑

              public void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                  doPost(request, response);

              }

              public void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                  request.setCharacterEncoding("utf-8");
                  // 開始組建的使用
                  DiskFileItemFactory factory = new DiskFileItemFactory();
                  ServletFileUpload upload = new ServletFileUpload(factory);

                  try {
                      List list = upload.parseRequest(request);// 解析傳過來的內容 返回LIST
                      Iterator it = list.iterator();// 對LIST進行枚舉
                      while (it.hasNext()) {
                          FileItem item = (FileItem) it.next();
                          // 判斷是文本信息還是對象(文件)
                          if (item.isFormField()) {
                              // 如果是文本信息返回TRUE
                              System.out.println("參數" + item.getFieldName() + ":"
                                      + item.getString("UTF-8"));
                              // 注意輸出值的時候要注意加上編碼
                          } else {
                              if (item.getName() != null && !item.getName().equals("")) {
                                  System.out.println("上傳文件的大小:" + item.getSize());
                                  System.out.println("上傳文件的類型:" + item.getContentType());
                                  System.out.println("上傳文件的名稱:" + item.getName());
                                  System.out.println(sc.getRealPath("/") + savePath);
                                  // 保存在服務器硬盤中
                                  File tempFile = new File(item.getName());// 臨時FILE對象
                                  // 此時有路徑的名字
                                  // TEMPFILE主要為了獲取文件的單純文件名
                                  File file = new File(sc.getRealPath("/") + savePath,
                                          "kdj"+(tempFile.getName()).substring((tempFile.getName()).length()-4,(tempFile.getName()).length()));
                                  //在這里可以更改名字   
                                  //用subString 的方法截取后綴 就可以加上自定義名稱放在第二個參數
                                  // 這個FILE是真正要保存的文件
                                  item.write(file);// 寫入服務器

                                  // 返回結果
                                  request.setAttribute("upload.message", "上傳成功");
                              } else {

                                  request.setAttribute("upload.message", "沒有選擇上傳文件");
                              }
                          }
                      }
                  } catch (FileUploadException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  } catch (Exception e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                      request.setAttribute("upload.message", "上傳沒成功");
                  }
                 
                  request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);

              }

              public void init(ServletConfig config) {
          //實現初始化文件   獲取初始化參數 路徑   和獲取 一個全局服務器對象 備用
                  savePath = config.getInitParameter("savePath");// 初始化綁定參數 表明保存在哪
                  sc = config.getServletContext();

              }

          }

          接收表單的servlet:flextest。java
          package org.zizi.test;

          import java.io.IOException;
          import java.io.PrintWriter;

          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import javax.servlet.http.HttpSession;

          public class FLEXTest extends HttpServlet {


              private static final long serialVersionUID = -154781975203117748L;

              public void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {

             
              }


              public void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {

                  response.setContentType("text/html;charset=utf-8");
                  request.setCharacterEncoding("utf-8");
                  String n=request.getParameter("username");
                  String m=request.getParameter("imageName");
                  request.setAttribute("pupload.message1", n);
                  request.setAttribute("pupload.message2", m);
                  request.getRequestDispatcher("/uploadResult2.jsp").forward(request, response);
          //FLEX會接收 這個轉向的JSP頁面動態生成的XML文件

              }

          }


          web。xml
            <servlet>
              <servlet-name>UploadServelt</servlet-name>
              <servlet-class>org.zizi.servlet.UploadServelt</servlet-class>
              <init-param>
              <param-name>savePath</param-name>
              <param-value>uploads</param-value>
              </init-param>
            </servlet>
            <servlet>
              <servlet-name>SendMailServlet</servlet-name>
              <servlet-class>org.zizi.sendMail.SendMailServlet</servlet-class>
            </servlet>

          uploadResult2.jsp
          <%@page language="java"  contentType="text/xml;charset=utf-8" pageEncoding="UTF-8"%><?xml version="1.0" encoding="utf-8"?>
          <cat>
              <dog name="${requestScope['pupload.message2']}">
              </dog>
              <dog name="${requestScope['pupload.message1']}">
              </dog>
          </cat>


          結果:
          servlet 輸出:
          參數Filename:安博之淚.jpg
          上傳文件的大小:124849
          上傳文件的類型:application/octet-stream
          上傳文件的名稱:安博之淚.jpg
          E:\tomcat6\webapps\webproject12\uploads
          參數Upload:Submit Query

          flex 輸出:
          [SWF] E:\workspaceforFlex\forwritingshop\bin-debug\test.swf - 926,895 bytes after decompression
          文件上傳成功 繼續傳送表單
          <cat><dog name="39254E3A-CC97-4FFE-8051-D152BF2A9E1F.jpg" /><dog name="zizi" /></cat>



          總結,完全可以全部傳送去一個SERVLET----UPLOAD,但是需要保存request的參數  可以建一個HashMap<String,String>(),然后保存參數。備以后存入數據庫使用。

          但是,需要調用兩次servlet。。。。因為Httpservice的contenttype沒有MULtiple/form-data。。。。??

          posted on 2010-08-17 14:39 junlin 閱讀(3099) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           

          導航

          <2010年8月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          2930311234

          統計

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 巴林右旗| 深州市| 舒城县| 通道| 仁化县| 泰宁县| 金乡县| 易门县| 本溪| 德保县| 章丘市| 肃南| 张家川| 伊吾县| 峡江县| 福海县| 招远市| 南郑县| 卢湾区| 剑川县| 航空| 福鼎市| 奎屯市| 商都县| 保靖县| 久治县| 内丘县| 土默特左旗| 化德县| 抚远县| 诸城市| 桐城市| 宜丰县| 阿巴嘎旗| 婺源县| 佛学| 天水市| 泸定县| 荆州市| 抚顺县| 昌黎县|