Use Flex and Servlet to upload files

Source: Internet
Author: User
Tags temporary file upload

Use Flex and Servlet to upload files


1. Preparations

(1) download File Upload components, commons-fileupload-1.3.1.jar

(2) download the file input and output jar, commons-io-2.4.jar

(3) The servlet jar package, servlet-api.jar


2. Formal Development

(1) create a web project, FlexFileUpload

(2) create a file upload servlet in src

FlexFileUploadServlet. java:

Package com. you. upload. servlet; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. util. iterator; import java. util. list; 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. fileItemFactory; import org. apache. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; public class FlexFileUploadServlet extends HttpServlet {/*** @ Fields serialVersionUID: serialization */private static final long serialVersionUID =-6839362803884547766L;/*** Constructor of the object. */public FlexFileUploadServlet () {super () ;}/ *** Destruction of the servlet.
*/Public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet.
** This method is called when a form has its tag value method equals to get. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {super. doGet (request, response); doPost (request, response);}/*** The doPost method of the servlet.
** This method is called when a form has its tag value method equals to * post. ** @ param request * the request send by the client to the server * @ param response * the response send by the server to the client * @ throws ServletException * if an error occurred *@ throws IOException * if an error occurred */@ SuppressWarnings ("rawtypes ") public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/*** prevents Chinese garbled characters */response. setContentType ("text/html; charset = gb2312");/*** set the encoding format */response. setCharacterEncoding ("UTF-8");/*** create a factory class */FileItemFactory factory = new DiskFileItemFactory (); /*** upload object */ServletFileUpload upload = new ServletFileUpload (factory); try {List items = upload. parseRequest (request); Iterator it = items. iterator (); while (it. hasNext () {FileItem item = (FileItem) it. next ();/*** determines the form field */if (item. isFormField () {System. out. println ("A form field");} else {/*** process File Upload */System. out. println ("not a form field"); String fileName = item. getName (); byte [] data = item. get ();/*** get the file upload path */String file = getServletConfig (). getInitParameter ("file"); String fileFolderName = getServletContext (). getRealPath (file + "\" + fileName); try {FileOutputStream fileOutSt = new FileOutputStream (fileFolderName); try {fileOutSt. write (data); fileOutSt. close ();} catch (IOException exception) {exception. printStackTrace () ;}} catch (FileNotFoundException exception) {exception. printStackTrace () ;}}} catch (FileUploadException exception) {exception. printStackTrace () ;}/ *** Initialization of the servlet.
** @ Throws ServletException * if an error occurs */public void init () throws ServletException {// Put your code here }}
(3) Configure web. xml

 
   
    
      
   
    
This is the description of my J2EE component
       
   
    
This is the display name of my J2EE component
       
   
    
FlexFileUploadServlet
       
   
    
Com. you. upload. servlet. FlexFileUploadServlet
       
           
    
     
Temporary File Upload path
            
    
     
File
            
    
     
File
        
     
    
      
   
    
FlexFileUploadServlet
       
   
    
/FlexFileUploadServlet
     
    
      
   
    
Index. jsp
     
  
 

(4) Open Flash Builder and create a Flex Project

FileUpload. mxml:

 
 
  
   
@ Namespace s "library: // ns.adobe.com/flex/spark"; @ namespace mx "library: // container"; Panel {borderStyle: solid; borderColor: # ff0000; borderAlpha: 0.5; borderThickness: 2; roundedBottomCorners: true; cornerRadius: 10; headerHeight: 50; backgroundAlpha: 0.5; highlightAlphas: 0.4, 0.24; headerColors: # cccc00, # cccccc00; footerColors: #660033; backgroundColor: #00 ffff; dropShadowEnabled: true; shadowDistance: 1; titleStyleName: "mypanelTitle ";}. mypanelTitle {letterSpacing: 1; color: # 6600cc; textAlign: left; fontFamily: Trebuchet MS; fontSize: 16; fontWeight: bold; fontStyle: italic; textDecoration: underline ;}
  
  import mx.collections.ArrayCollection;import mx.controls.Alert;import mx.events.FlexEvent;[Bindable]//提示用户选择要上载的文件或用于下载的位置private var fileRefer:FileReference;[Bindable]//判断文件是否选中private var fileSelected:Boolean;[Bindable]//上传文件临时路径private var serverURL:String = "http://localhost:8686/FlexFileUpload/FlexFileUploadServlet";private var stat:Array = new Array();[Bindable]private var statusArray:ArrayCollection = new ArrayCollection();/** * 初始化函数 */protected function initHandler():void{fileRefer = new FileReference();fileRefer.addEventListener(Event.SELECT, onFileSelect); fileRefer.addEventListener(ProgressEvent.PROGRESS,onUploadProgress); fileRefer.addEventListener(Event.COMPLETE, onUploadComplete); fileRefer.addEventListener(IOErrorEvent.IO_ERROR, onUploadError); fileRefer.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError); }/** * 选择文件事件函数 */private function onFileSelect(event:Event):void { fileSelected = true; fileTxt.text = fileRefer.name; stat.push({status:"准备上传 "+fileTxt.text});            statusArray = new ArrayCollection(stat); } /** * 正在上传事件函数  */private function onUploadProgress(event:ProgressEvent):void { stat.push({status:"进度.."+((event.bytesLoaded * 100) / event.bytesTotal).toString()+"%"}); statusArray = new ArrayCollection(stat); } /** * 上传完全事件函数  */private function onUploadComplete(event:Event):void { stat.push({status:"上传成功!"}); statusArray = new ArrayCollection(stat); } /** * 上传出现错误事件函数  */private function onUploadError(event:Event):void { if (event is IOErrorEvent) { stat.push({status:"输入输出错误: "+(event as IOErrorEvent).text.toString()}); statusArray = new ArrayCollection(stat); } else if (event is SecurityErrorEvent) { stat.push({status:"安全错误: "+(event as IOErrorEvent).text.toString()}); statusArray = new ArrayCollection(stat); } }/** * 浏览按钮事件函数  */protected function uploadBtn_clickHandler(event:MouseEvent):void{fileRefer.browse(); }/** * 上传文件事件函数  */protected function uploadClickHandler(event:MouseEvent):void{if (!fileSelected || (urlTxt.text.length == 0)) { Alert.show("请选择一个文件并选择路径"); return; } var urlRequest:URLRequest = new URLRequest(urlTxt.text); fileRefer.upload(urlRequest);}
  
  
   
  
  
   
    
     
      
     
     
      
     
     
      
     
    
    
       
        
       
       
        
       
    
      
       
      
      
       
       
        
        
        
       
      
   
  
 

3. Running result

(1) During Initialization



<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + o6gyo6nJz7SrzsS8/g0vcd4kpha + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140428/20140428091205119.jpg" width = "402" height = "406" border = "1" alt = "\">


(3) Before uploading files, the Server file Folder



(4) The Server file Folder after the file is uploaded



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.