Flex batch upload through Servlet
19:28:06 | category:
Flex & Air | Tag: Batch upload of flex Java Servlet
| Large font size, medium/small subscription
1. servlet code
Package com. FPT. 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;
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;
/**
* Servlet for uploading pages in page
*
* @ Author Zhang Long
* @ Version 1.0
* @ Date 09-12-15
*/
Public class fileuploadservlet extends httpservlet {
// Define the File Upload path
Private string uploadpath = "F :/";
// Restrict the file upload size
Private int maxpostsize = 100*1024*1024;
Public fileuploadservlet (){
Super ();
}
Public void destroy (){
Super. Destroy ();
}
Protected void processrequest (httpservletrequest request,
Httpservletresponse response) throws servletexception, ioexception {
System. Out. println ("access! ");
// Uploadpath = request. getsession (). getservletcontext (). getrealpath ("");
System. Out. println (uploadpath );
Response. setcontenttype ("text/html; charset = UTF-8 ");
Printwriter out = response. getwriter ();
// Save the file to the server
Diskfileitemfactory factory = new diskfileitemfactory ();
Factory. setsizethreshold (4096 );
Servletfileupload upload = new servletfileupload (factory );
Upload. setsizemax (maxpostsize );
Try {
List fileitems = upload. parserequest (request );
Iterator iter = fileitems. iterator ();
While (ITER. hasnext ()){
Fileitem item = (fileitem) ITER. Next ();
If (! Item. isformfield ()){
String name = item. getname ();
System. Out. println (name );
Try {
Item. Write (new file (uploadpath + name ));
// SaveFile S = new SaveFile ();
// S. SaveFile (name );
} Catch (exception e ){
E. printstacktrace ();
}
}
}
} Catch (fileuploadexception e ){
E. printstacktrace ();
System. Out. println (E. getmessage () + "end ");
}
}
// <Editor-fold defaultstate = "Collapsed"
// DESC = "httpservlet methods. Click on the + sign on the left to edit the CODe. ">
Protected void doget (httpservletrequest request,
Httpservletresponse response) throws servletexception, ioexception {
Processrequest (request, response );
}
Protected void dopost (httpservletrequest request,
Httpservletresponse response) throws servletexception, ioexception {
Processrequest (request, response );
}
/**
* Returns a short description of the servlet.
*/
Public String getservletinfo (){
Return "File Upload ";
}
}
2. Flex Upload Component
<? XML version = "1.0" encoding = "UTF-8"?>
<Mx: Panel xmlns: MX = "http://www.adobe.com/2006/mxml" ispopup = "true"
Layout = "vertical" width = "100%" minwidth = "400" Height = "100%" minheight = "200"
Title = "upload page" creationcomplete = "initcom ()">
<Mx: Metadata>
[Event (name = "uploadcomplete", type = "flash. Events. Event")]
[Event (name = "uploadprogress", type = "flash. Events. progressevent")]
[Event (name = "uploadcancel", type = "flash. Events. Event")]
[Event (name = "uploadioerror", type = "flash. Events. ioerrorevent")]
[Event (name = "uploadsecurityerror", type = "flash. Events. securityerrorevent")]
</MX: Metadata>
<Mx: SCRIPT>
<! [CDATA [
/*
Written:
Dustin Andrew
Dustin@flash-dev.com
Www.flash-dev.com
Fileupload
Panel component for uploading files.
(Icons from http://www.famfamfam.com)
Last Updated:
12/15/06
*/
IMPOrt mx. Controls .*;
IMPOrt mx. Managers .*;
IMPOrt mx. Events .*;
IMPORT flash. Events .*;
IMPORT flash.net .*;
Private VaR _ struploadurl: string;
Private VaR _ refaddfiles: filereferencelist;
Private VaR _ refuploadfile: filereference;
Private VaR _ arruploadfiles: array;
Private VaR _ numcurrentupload: Number = 0;
// Set uploadurl
Public Function set uploadurl (struploadurl: string): void {
_ Struploadurl = struploadurl;
}
// Initalize
Private function initcom (): void {
_ Arruploadfiles = new array ();
Enableui ();
Uploadcheck ();
}
// Called to add file (s) for upload
Private function addfiles (): void {
_ Refaddfiles = new filereferencelist ();
_ Refaddfiles. addeventlistener (event. select, onSelectfile );
_ Refaddfiles. Browse ();
}
// Called when a file is selected
Private function onSelectfile (Event: Event): void {
VaR arrfoundlist: array = new array ();
// Get list of files from filelist, make list of files already on upload list
For (var I: Number = 0; I <_ arruploadfiles. length; I ++ ){
For (var j: Number = 0; j <_ refaddfiles. filelist. length; j ++ ){
If (_ arruploadfiles [I]. Name = _ refaddfiles. filelist [J]. Name ){
Arrfoundlist. Push (_ refaddfiles. filelist [J]. Name );
_ Refaddfiles. filelist. splice (J, 1 );
J --;
}
}
}
If (_ refaddfiles. filelist. length> = 1 ){
For (var k: Number = 0; k <_ refaddfiles. filelist. length; k ++ ){
_ Arruploadfiles. Push ({
Name: _ refaddfiles. filelist [K]. Name,
Size: formatfilesize (_ refaddfiles. filelist [K]. Size ),
File: _ refaddfiles. filelist [k]});
}
Listfiles. dataprovider = _ arruploadfiles;
Listfiles. selectedindex = _ arruploadfiles. Length-1;
}
If (arrfoundlist. length> = 1 ){
Alert. Show ("the file (s): \ n? "+ Arrfoundlist. Join (" \ n? ") +" \ N... are already on the upload list. please change the filename (s) or pick a different file. "," file (s) already on List ");
}
Updateprogbar ();
Scrollfiles ();
Uploadcheck ();
}
// Called to format number to file size
Private function formatfilesize (numsize: Number): String {
VaR strreturn: string;
Numbersize = Number (numsize/1000 );
Strreturn = string (numsize. tofixed (1) + "kb ");
If (numsize & gt; 1000 ){
Numsize = numsize/1000;
Strreturn = string (numsize. tofixed (1) + "MB ");
If (numsize & gt; 1000 ){
Numsize = numsize/1000;
Strreturn = string (numsize. tofixed (1) + "GB ");
}
}
Return strreturn;
}
// Called to Remove selected file (s) for upload
Private function removefiles (): void {
VaR arrselected: array = listfiles. selectedindices;
If (arrselected. length> = 1 ){
For (var I: Number = 0; I <arrselected. length; I ++ ){
_ Arruploadfiles [number (arrselected [I])] = NULL;
}
For (var j: Number = 0; j <_ arruploadfiles. length; j ++ ){
If (_ arruploadfiles [J] = NULL ){
_ Arruploadfiles. splice (J, 1 );
J --;
}
}
Listfiles. dataprovider = _ arruploadfiles;
Listfiles. selectedindex = 0;
}
Updateprogbar ();
Scrollfiles ();
Uploadcheck ();
}
// Called to check if there is at least onE file to upload
Private function uploadcheck (): void {
If (_ arruploadfiles. Length = 0 ){
Btnupload. Enabled = false;
Listfiles. verticalscrollpolicy = "off ";
} Else {
Btnupload. Enabled = true;
Listfiles. verticalscrollpolicy = "on ";
}
}
// Disable UI control
Private function disableui (): void {
Btnadd. Enabled = false;
Btnremove. Enabled = false;
Btnupload. Enabled = false;
Btncancel. Enabled = true;
Listfiles. Enabled = false;
Listfiles. verticalscrollpolicy = "off ";
}
// Enable UI control
Private function enableui (): void {
Btnadd. Enabled = true;
Btnremove. Enabled = true;
Btnupload. Enabled = true;
Btncancel. Enabled = false;
Listfiles. Enabled = true;
Listfiles. verticalscrollpolicy = "on ";
}
// Scroll listfiles to selected row
Private function scrollfiles (): void {
Listfiles. verticalscrollposition = listfiles. selectedindex;
Listfiles. validatenow ();
}
// Called to upload file based on current upload number
Private function startupload (): void {
If (_ arruploadfiles. length> 0 ){
Disableui ();
Listfiles. selectedindex = _ numcurrentupload;
Scrollfiles ();
// Variables to send along with upload
VaR sendvars: urlvariables = new urlvariables ();
Sendvars. ActIon = "Upload ";
VaR request: URLRequest = new URLRequest ();
Request. DaTa = sendvars;
Request. url = _ struploadurl;
Request. method = urlrequestmethod. post;
_ Refuploadfile = new filereference ();
_ Refuploadfile = listfiles. selecteditem. file;
_ Refuploadfile. addeventlistener (progressevent. Progress, onUploadprogress );
_ Refuploadfile. addeventlistener (event. Complete, onUploadcomplete );
_ Refuploadfile. addeventlistener (ioerrorevent. io_error, onUploadioerror );
_ Refuploadfile. addeventlistener (securityerrorevent. security_error, onUploadsecurityerror );
_ Refuploadfile. Upload (request, "file", false );
}
}
// Cancel and clear eventlisteners on last upload
Private function clearupload (): void {
_ Refuploadfile. removeeventlistener (progressevent. Progress, onUploadprogress );
_ Refuploadfile. removeeventlistener (event. Complete, onUploadcomplete );
_ Refuploadfile. removeeventlistener (ioerrorevent. io_error, onUploadioerror );
_ Refuploadfile. removeeventlistener (securityerrorevent. security_error, onUploadsecurityerror );
_ Refuploadfile. Cancel ();
_ Numcurrentupload = 0;
Updateprogbar ();
Enableui ();
}
// Called on upload cancel
Private function onUploadcanceled (): void {
Clearupload ();
Dispatchevent (new event ("uploadcancel "));
}
// Get upload progress
Private function onUploadprogress (Event: progressevent): void {
VaR numperc: Number = math. Round (event. bytesloaded/event. bytestotal) * 100 );
Updateprogbar (numperc );
VaR EVT: progressevent = new progressevent ("uploadprogress", false, false, event. bytesloaded, event. bytestotal );
Dispatchevent (EVT );
}
// Update progbar
Private function updateprogbar (numperc: Number = 0): void {
VaR strlabel: String = (_ numcurrentupload + 1) + "/" + _ arruploadfiles. length;
Strlabel = (_ numcurrentupload + 1 <= _ arruploadfiles. Length & numperc> 0 & numperc <100 )? Numperc + "%-" + strlabel: strlabel;
Strlabel = (_ numcurrentupload + 1 = _ arruploadfiles. Length & numperc = 100 )? "Upload complete-" + strlabel: strlabel;
Strlabel = (_ arruploadfiles. Length = 0 )? "": Strlabel;
Progbar. Label = strlabel;
Progbar. setprogress (numperc, 100 );
Progbar. validatenow ();
}
// Called on Upload complete
Private function onUploadcomplete (Event: Event): void {
_ Numcurrentupload ++;
If (_ numcurrentupload <_ arruploadfiles. Length ){
Startupload ();
} Else {
Enableui ();
Clearupload ();
Dispatchevent (new event ("uploadcomplete "));
}
}
// Called on upload Io Error
Private function onUploadioerror (Event: ioerrorevent): void {
Clearupload ();
VaR EVT: ioerrorevent = new ioerrorevent ("uploadioerror", false, false, event. Text );
Dispatchevent (EVT );
}
// Called on upload security error
Private function onUploadsecurityerror (Event: securityerrorevent): void {
Clearupload ();
VaR EVT: securityerrorevent = new securityerrorevent ("uploadsecurityerror", false, false, event. Text );
Dispatchevent (EVT );
}
// Change view State
Private function changeview (): void {
Currentstate = (currentstate = "mini ")? "": "Mini ";
}
]>
</MX: SCRIPT>
<Mx: States>
<Mx: State name = "mini">
<Mx: setproperty name = "height" value = "60"/>
<Mx: setproperty name = "minheight" value = "60"/>
<Mx: setstyle target = "{btnview}" name = "icon" value = "@ embed (& apos; IMGs/icons/upload/application_put.png & apos;)"/>
</MX: State>
</MX: States>
<Mx: Transitions>
<Mx: Transition fromstate = "*" tostate = "*">
<Mx: resize target = "{This}" Duration = "1000"/>
</MX: Transition>
</MX: Transitions>
<Mx: canvas width = "100%" Height = "100%">
<Mx: DataGrid id = "listfiles" Left = "0" Top = "0" Bottom = "0" Right = "0"
Allowmultipleselection = "true" verticalscrollpolicy = "on"
Draggablecolumns = "false" resizablecolumns = "false" sortablecolumns = "false">
<Mx: columns>
<Mx: datagridcolumn headertext = "Page name" datafield = "name" wordwrap = "true"/>
<Mx: datagridcolumn headertext = "page size" datafield = "size" width = "75"/>
</MX: columns>
</MX: DataGrid>
</MX: canvas>
<Mx: controlbar horizontalalign = "center" verticalalign = "Middle">
<Mx: button id = "btnadd" tooltip = "add file (s)" Click = "addfiles ()" icon = "@ embed (& apos; IMGs/icons/upload/add.png & apos;) "width =" 26 "/>
<Mx: button id = "btnremove" tooltip = "Remove file (s)" Click = "removefiles ()" icon = "@ embed (& apos; IMGs/icons/upload/delete.png & apos;) "width =" 26 "/>
<Mx: progressbar id = "progbar" mode = "Manual" label = "" labelplacement = "center" width = "100%"/>
<Mx: button id = "btncancel" tooltip = "cancel upload" icon = "@ embed (& apos; IMGs/icons/upload/cancel2.png & apos ;) "width =" 26 "Click =" onUploadcanceled () "/>
<Mx: button label = "Upload" tooltip = "Upload file (s)" id = "btnupload" Click = "startupload ()" icon = "@ embed (& apos; IMGs/icons/upload/bullet_go.png & apos;) "/>
<Mx: button id = "btnview" tooltip = "show/hide file (s)" icon = "@ embed (& apos; IMGs/icons/upload/application_get.png & apos ;) "width =" 26 "Click =" changeview () "/>
</MX: controlbar>
</MX: Panel>
3. Flex main program
<Application>
<SCRIPT>
// Upload File-related variables
Private const _ strdomain: String = new string ("http: // 192.168.1.99 /");
// Private const _ struploadscript: String = new string (_ strdomain + "files/fileupload/upload. php ");
Private const _ struploadscript: String = new string ("http: // 192.168.1.99: 8080/FPT/fileupload ");
Security. allowdomain (_ strdomain); // Security Settings
</SCRIPT>
<! -- Upload a subpage -->
<Upload: fileupload
Width = "411" Height = "170"
Uploadurl = "{_ struploadscript }"
Uploadcomplete = "alert. Show (& apos; file (s) have been uploaded. & apos;, & apos; upload successful & apos ;)"
Uploadioerror = "alert. Show (& apos; IO error in uploading file. & apos;, & apos; error & apos ;)"
Uploadsecurityerror = "alert. show (& apos; security error in uploading file. & apos;, & apos; error & apos;) "x =" 562 "Y =" 39 "/>
</Application>