File upload and download in flex

Source: Internet
Author: User

Like traditional JSP, In Flex, file upload and download functions are also required. However, in flex, file upload and download are relatively complicated, see the following for how to implement it.

Since Flex is a relatively new technology, we tried it in JSP mode during the research. At the beginning, we mainly had the following ideas:

A. use ftp to upload and download files. Use the flex socket interface.

B. Use WebService to upload and download files

C. Use the Flex + sevlet + fileupload component to upload and download files.

After comparison, the third method is selected. The Flex + sevlet method is used to upload and download files. The reasons are as follows (corresponding to the above ideas ):

A. operations involving streams are complicated to implement, and the probability of errors is high.

B. There is little reference to the flex end and the WebService Service needs to be started.

C. This technology is quite mature. Since flex2.0, filereference classes can be referenced on the flex end, and mature components can be used on the Java end, so we finally consider using this method for processing.

I. File Upload
1. Flex end
A. Introduction to the classes used:
The filereference class provides a method for uploading and downloading files between the user's computer and the server. The operating system dialog box prompts you to select the file to be uploaded or the location for download. It mainly uploads a file.
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.
B. Use the filereferencelist class to upload multiple files:
1) instantiate the class: var myfileref = new filereferencelist ();
2) 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 ();
3) after the Browse () method is successfully called, use the filereference object array to fill in the filelist attribute of the filereferencelist object.
Call filereference. Upload () for each element in the filelist array ()

The Code is as follows:

/***//**
* Perform the upload operation.
**/
Private function uploadfiles (): void
{
Try
{
Selectfilelist. Browse (new array (imagefilter, textfilter ));
Selectfilelist. addeventlistener (event. Select, selecthandler1 );
}
Catch (error: Error)
{
Alert. Show ("incorrect file selection; select the correct file ");
}
}
/***//**
* If the file is selected, run this method.
**/
Function selecthandler1 (Event: Event): void
{
VaR request: URLRequest = new URLRequest ("fileuploadservlet ");
VaR uploadfile: filereference;
VaR uploadfilelist: filereferencelist = filereferencelist(event.tar get );
VaR selectedfilearray: array = uploadfilelist. filelist;
Login = (testpress) (popupmanager. createpopup (this, testpress, true ));
For (var I: uint = 0; I <selectedfilearray. length; I ++)
{
Uploadfile = filereference (selectedfilearray [I]);
Uploadfile. addeventlistener (event. Complete, uploadcompletehandler );
Uploadfile. addeventlistener (progressevent. Progress, progresshandler );
Try
{
Uploadfile. Upload (request );
}
Catch (error: Error)
{
Alert. Show (error. Message. tostring ());
}
}
}
Function uploadcompletehandler (Event: Event): void
{
VaR uploadfiles: filereference = filereference(event.tar get );
VaR filenames = uploadfiles. Name;
// Alert. Show ('file '+ filenames + 'uploaded successfully ')
Login. mylabels. Text = 'filenames + 'uploaded successfully ';
}
Private function progresshandler (E: progressevent): void
{
VaR proc: uint = E. bytesloaded/E. bytestotal * 100;
Login. Bar. setprogress (Proc, 100 );
Login. Bar. Label = "current progress:" + "" + proc + "% ";
}

Testpress. mxml

<? XML version = "1.0" encoding = "UTF-8"?>
<Mx: titlewindow xmlns: MX = "http://www.adobe.com/2006/mxml" layout = "absolute" width = "528" Height = "236">
<Mx: SCRIPT>
<! [CDATA [
Import MX. Managers. popupmanager;
Public Function clickme (): void {
Popupmanager. removepopup (this );
}
]>
</MX: SCRIPT>
<Mx: progressbar id = "bar" labelplacement = "bottom" themecolor = "# f20d7a"
Minimum = "0" visible = "true" Maximum = "100" label = "current progress: 0%"
Direction = "right" mode = "Manual" width = "200" x = "154" Y = "84"/>
<Mx: button x = "221" Y = "135" label = "close" Click = "clickme ();"/>
<Mx: Label x = "173" Y = "27" id = "mylabels" width = "157"/>

</MX: titlewindow>

 

2. Java end

Accept requests from flex and use Apache's fileupload class library in Java to implement the upload function. The Code is as follows:

 

Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. util. iterator;
Import java. util. List;
Import java. util. properties;

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 fileuploadservlet extends httpservlet
{

// Private string uploadpath = "D: // upload //";
Private string Path = "file_path.properties ";
Private string skstr = "";
Private string uploadpath = "";
Private int maxpostsize = 1000*1024*1024;

Public void dopost (httpservletrequest req, httpservletresponse res) throws servletexception,
Ioexception
{
String filepathaa = This. getservletconfig (). getservletcontext (). getrealpath ("/");

Properties P = loadproperties (PATH );

Uploadpath = P. getproperty ("filepath ");

Res. setcontenttype ("text/html; charset = UTF-8 ");
Req. setcharacterencoding ("UTF-8 ");

Diskfileitemfactory factory = new diskfileitemfactory ();
Factory. setsizethreshold (1024*20 );

Servletfileupload upload = new servletfileupload (factory );
Upload. setsizemax (maxpostsize );
Try
{
List fileitems = upload. parserequest (req );
Iterator iter = fileitems. iterator ();
While (ITER. hasnext ())
{
Fileitem item = (fileitem) ITER. Next ();
If (! Item. isformfield ())
{
String name = item. getname ();

Try
{
File skfile = new file (uploadpath + name );
If (skfile. exists ())
{
Skfile. Delete ();
Item. Write (new file (uploadpath + name ));

}
Else
{
Item. Write (new file (uploadpath + name ));
}

} Catch (exception E)
{
E. printstacktrace ();
}
}
}
} Catch (fileuploadexception E)
{
E. printstacktrace ();
}

}

Public properties loadproperties (string path) throws ioexception
{

Inputstream in = This. getclass (). getresourceasstream (PATH );
//

Properties P = new properties ();

P. Load (in );
In. Close ();
Return P;
}

}

Modify web. xml and add the following content:

 

<! -- For File Uploaded -->
<Servlet>
<Servlet-Name> fileuploadservlet </servlet-Name>
<Servlet-class> fileuploadservlet </servlet-class>
</Servlet>

<Servlet-mapping>
<Servlet-Name> fileuploadservlet </servlet-Name>
<URL-pattern>/fileuploadservlet </url-pattern>
</Servlet-mapping>

Ii. File Download

Call method: Private function downloadfiles (urladd: string): void
The urladd parameter is the user's IP address. If you use a local localhost, a Security Sandbox problem occurs. Therefore, you can enter your own IP address. This avoids the Security Sandbox issue. If the service is started on the local machine and the access address needs to be entered, you cannot use localhost instead of the local IP address. Otherwise, the Security Sandbox problem still occurs.

The filereference. Download () method prompts you to provide the file storage location and start downloading from a remote URL. Directly load the Request Path for download without background support. The Code is as follows:

 

Import com. systex. Flex. util. testpress;

Import flash.net. filereferencelist;

Import MX. Controls. Alert;
Import MX. Managers. popupmanager;
VaR imagefilter: filefilter = new filefilter ("image files (*. JPG ,*. JPEG ,*. GIF ,*. PNG )","*. JPG ;*. JPEG ;*. GIF ;*. PNG ");
VaR textfilter: filefilter = new filefilter ("text files (*. TXT ,*. RTF ,*. zip )","*. txt ;*. RTF ;*. zip ");
VaR selectfilelist: filereferencelist = new filereferencelist ();
VaR selectedfilearray: array = new array ();
VaR login: testpress = new testpress ();
VaR DownLoadURL: URLRequest;
VaR downloadfile: filereference; // This is the main part.
// Http://XX.XX.XX.XX: 8080/upload/main.zip
Private function downloadfiles (urladd: string): void
{
DownLoadURL = new URLRequest (urladd );
Downloadfile = new filereference ();
Configurelisteners (downloadfile );
Downloadfile. Download (DownLoadURL );
}
Private function configurelisteners (Dispatcher: ieventdispatcher): void {
Dispatcher. addeventlistener (event. Complete, completehandler );

}

Private function completehandler (Event: Event): void {
MX. Controls. Alert. Show ("file downloaded successfully ");
}

Here is the previous part of the uploaded code.

Attaching the tested mxml

 

<? XML version = "1.0" encoding = "UTF-8"?>
<Mx: Application xmlns: MX = "http://www.adobe.com/2006/mxml" layout = "absolute"
>
<Mx: script source = "updownloadfiles. As"/>

<Mx: canvas width = "100%" Height = "100%" x = "10" Y = "170" fontsize = "15">
<Mx: vbox width = "100%" horizontalalign = "center">
<Mx: textinput id = "mytextinput"/>
<Mx: button label = "File Download" Click = "downloadfiles ('HTTP: // '+ mytextinput. Text +': 8080/downloading/2msn.rar ');"/>
<Mx: button label = "Upload File" Click = "uploadfiles ();"/>
</MX: vbox>
</MX: canvas>
</MX: Application>

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.