Java and flex learning notes (8) -- flex Multifile upload with progress bar (based on servlet)

Source: Internet
Author: User

The file upload implemented in flex mainly uses the following two classes:


● Filereference: The filereference class provides a method for uploading and downloading files between the user's computer and server. The operating system dialog box prompts you to select the file to be uploaded or the location for download. Each filereference object references a file on the user's disk and has some attributes, including the file size, type, name, and creation date.(Creationdate), Modify the date (modificationdate) and creator type (Macintosh only) information.


● The filereferencelist class allows you to select one or more files to upload. The filereferencelist object represents a group of local files (one or more files) on the user disk as an array of filereference objects. For more information and important considerations about the filereference object and the filereference class (which can be used with filereferencelist), see the filereference class.


The filereferencelist class is used as follows:


① Instantiate this class: var myfileref = new filereferencelist ();


② Call the filereferencelist. Browse () method. This method opens a dialog box that allows you to select one or more files to be uploaded: myfileref. Browse ();


③ After the Browse () method is successfully called, The filereference object array is used to fill in the filelist attribute of the filereferencelist object.


④ Call filereference. Upload () for each element in the filelist array ().


Now, start File Upload. First, create an application file uploadfiledemo. mxml. The Code is as follows:


<? Xmlversion = "1.0" encoding = "UTF-8"?> <S: Application xmlns: FX = "http://ns.adobe.com/mxml/2009" xmlns: S = "Library: // ns.adobe.com/flex/spark" xmlns: MX = "Library: // ns.adobe.com/flex/mx "minwidth =" 955 "minheight =" 600 "applicationcomplete =" application_initializehandler (event) "> <FX: SCRIPT> <! [CDATA [import ases. filereferencevo; import flashx. textlayout. events. selectionevent; import MX. collections. arraycollection; import MX. controls. alert; import MX. events. closeevent; import MX. events. flexevent; import MX. RPC. events. faultevent; import spark. primitives. supportclasses. filledelement; Public varselectfilelist: filereferencelist = new filereferencelist (); // storage array of the selected file [Bindable] public var filea Rraycollction: arraycollection = newarraycollection (); // This array is used to save the file information [Bindable] public var arraycollection: arraycollection = newarraycollection (); // This array is used to display public varurlrequest: URLRequest = new URLRequest ("http: // localhost: 9080/javaandflex/fileuploadservlet") in the DataGrid table "); // server class address: protected function application_initializehandler (Event: flexevent): void {// todoauto-generated method stub selectfilelist. add Eventlistener (event. select, selectfilehandler); // select file listener} public function selectfiles (): void {// View File Processing Event // arraycollection. removeall (); var imagesfilter: filefilter = new filefilter ("Images ","*. JPG ;*. GIF ;*. PNG "); // The selected image type var docfilter: filefilter = new filefilter (" documents ","*. pdf ;*. doc ;*. TXT "); // The selected document type var videofilter: filefilter = new filefilter (" videos ","*. MP3 ;*. MP4 ;*. avi ;*. rmvb "); // select the video Type: selectfilelist. browse ([imagesfilter, docfilter, videofilter]);} public function selectfilehandler (Event: Event): void {// process the selected file for (var I: Int = 0; I <selectfilelist. filelist. length; I ++) {varfilereference: filereference = filereference (selectfilelist. filelist [I]); var object: Object = new object (); object. filerefer = filereference; object. filename = filereference. name; object. filetype = filereference. type. substr (1 ); Object. filesize = (filereference. size/1024 ). tofixed (2) + "kb"; filearraycollction. additem (object); arraycollection. additem (object);} filedatagrid. dataprovider = arraycollection;} protected function cancleupload_clickhandler (Event: mouseevent): void // Clear button handler {// todoauto-generated method stub alert. yeslabel = "yes"; alert. cancellabel = "cancel" If (filearraycollction. length <1) {alert. show ("no file to upload! "," Prompt "); return;} alert. Show (" are you sure you want to clear the File Upload list? "," Prompt ", alert. yes | alert. cancel, this, yesorcanclehandler, null, alert. cancel);} public function yesorcanclehandler (Event: closeevent): void {If (event. detail = alert. yes) {arraycollection. removeall (); filearraycollction. removeall (); filedatagrid. dataprovider = arraycollection;} protected function uploadfile_clickhandler (Event: mouseevent): void // File Upload handler {// todoauto-generated method stub if (filearraycoll Ction. Length <1) {alert. Show ("select the file to upload! "," Prompt "); return;} For (var I: Int = 0; I <filearraycollction. length; I ++) {varfilereference: filereference = filereference (filearraycollction [I] ['filerefer']); // fileupload. upload (filereference. data, filereference. name); filereference. upload (URLRequest); browsefile. enabled = false; // set the Browse File button to uploadfile. enabled = false; // set the upload button to cancleupload. enabled = false; // set the Clear button to gray if (I = filearraycollction. length-1) {filerefe Rence. addeventlistener (event. complete, fileuploadcompletehandler) ;}} protected function fileuploadcompletehandler (Event: Event): void {browsefile. enabled = true; uploadfile. enabled = true; cancleupload. enabled = true; alert. yeslabel = "yes"; alert. cancellabel = "no"; alert. show ("the file has been uploaded. Are you sure you want to continue uploading? "," Prompt ", alert. yes | alert. cancel, this, chooseuploadfile, null, alert. cancel);} protected function chooseuploadfile (Event: closeevent): void {// processing function if (event. detail = alert. yes) {This. selectfiles () ;}}]> </FX: SCRIPT> <FX: declarations> <! -- Place non-visualelements (e.g ., services, value objects) Here --> </FX: declarations> <s: panel x = "304" Y = "131" width = "717" Height = "380" Title = "File Upload" fontsize = "18"> <mx: dataGrid x = "25" Y = "14" id = "filedatagrid" fontweight = "bold" width = "669" fontsize = "16" Height = "261"> <mx: columns> <mx: datagridcolumn headertext = "file name" width = "200" datafield = "FILENAME"/> <mx: datagridcolumn headertext = "file size" width = "100 "Datafield =" filesize "/> <mx: datagridcolumn headertext =" file type "width =" 100 "datafield =" filetype "/> <mx: datagridcolumn headertext = "Upload progress"> <mx: itemrenderer> <FX: component> <mx: hbox width = "100%" Height = "100%" paddingleft = "10"> <FX: SCRIPT> <! [CDATA [importmx. collections. arraycollection; protected functionefile_clickhandler (Event: mouseevent): void {// todo auto-generated method stub // var grid: object ready event.tar get. parent. parent. parent; var DP: arraycollection = arraycollection (grid. dataprovider); var index: Int = DP. getitemindex (data); outerdocument. arraycollection. removeitemat (INDEX); DP. removeitemat (INDEX); grid. parent. refresh ();} protected functionssbar_progresshandler (Event: progressevent): void {// todo auto-generated method stub deletefile. visible = false;} protected function progressbar_completehandler (Event: Event): void {// todo auto-generated method stub deletefile. visible = true ;}]]> </FX: SCRIPT> <mx: progressbar minimum = "0" chromecolor = "13892729" Maximum = "100" Progress = "progressbar_progresshandler (Event) "Complete =" progressbar_completehandler (event) "labelplacement =" center "Source =" {data. filerefer} "label =" % 3% % "id =" progressbar "width =" 90% "/> <mx: linkbutton id = "deletefile" width = "10%" icon = "@ embed ('images/delete.png ')" Click = "deletefile_clickhandler (event)"/> </MX: hbox> </FX: component> </MX: itemrenderer> </MX: datagridcolumn> </MX: columns> </MX: DataGrid> <mx: hbox paddingleft = "20" horizontalgap = "35" paddingtop = "8" x = "218" Y = "295" width = "100%" Height = "100%"> <s: button id = "browsefile" Height = "31" label = "Browse... "fontsize =" 18 "Click =" selectfiles () "/> <s: button id = "uploadfile" Height = "31" label = "Upload" fontsize = "18" Click = "uploadfile_clickhandler (event)"/> <s: button id = "cancleupload" Height = "31" label = "clear" fontsize = "18" Click = "cancleupload_clickhandler (event)"/> </MX: hbox> </S: Panel> </S: Application>

The runtime page is as follows:




Create a servlet-type fileuploadservlet with the following code:


Package COM. ldfsoft. servlet; import Java. io. file; import Java. io. ioexception; import Java. io. printwriter; import Java. util. iterator; import Java. util. list; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; importjavax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; importorg. apache. commons. fileupload. fileitem; importorg. apache. commons. fileupload. f Ileuploadexception; importorg. apache. commons. fileupload. disk. diskfileitemfactory; importorg. apache. commons. fileupload. servlet. servletfileupload; public class fileuploadservlet extendshttpservlet {@ unchecked ("unchecked") @ overrideprotected void Service (response, httpservletresponse response) handle, ioexception {// todo auto-generated method stuse. SETCO Ntenttype ("text/html; charset = UTF-8"); diskfileitemfactory = newdiskfileitemfactory (); servletfileupload = newservletfileupload (diskfileitemfactory); servletfileupload. setheaderencoding ("UTF-8"); servletfileupload. setsizemax (1024*1024*1024); try {list <fileitem> items = servletfileupload. parserequest (request); iterator <fileitem> iterator = items. iterator (); While (iterato R. hasnext () {fileitemitem = (fileitem) iterator. Next (); If (! Item. isformfield () {stringfilename = item. getname (); stringpath = getservletcontext (). getrealpath ("/") + "files/"; // The File Upload directory is the system in the Files folder under the root directory. out. println (filename); fileuploadfile = new file (path + filename); item. write (uploadfile) ;}} catch (fileuploadexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (exception e) {// todo auto-generated Catch Block E. printstacktrace ();}}}

 

Note that this Servlet File requires two jar packages: commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar, which I use in struts2.2.1.1.


Start to select a file:



After clicking the upload button, the file starts to be uploaded. Because the local upload speed is quite fast, small files are just a matter of time. The "Browse" button, "Upload" button, and "clear" button are all grayed out, And the delete button after the progress bar is invisible, as shown in the following figure:




After the upload is complete, the three buttons resume normal and you will be prompted to continue uploading, as shown below:




Well, the demonstration is complete. This is the result of the two days of work. If you think it is good, you can support me. The first time you did this, it was quite fortunate. Next I decided to download the file and look forward to it...


Original article, reproduced please indicate the source: http://www.dianfusoft.com/




Related Article

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.