Upload and download in Java

Source: Internet
Author: User
Tags constant definition temporary file storage

4.4.1 development of the struts2 file upload function
Technical Points
This section describes in detail the development process of the file upload function. The knowledge points are as follows:
 
= File upload page and code content displayed on the successfully uploaded page.
 
= Introduction to the upload function and object attributes in the uploadaction class.
 
= Configuration of uploadaction, character encoding, and temporary file storage path in struts. xml.
 
= The path after the upload and the effect after the final upload are displayed.
 
DEMO code
Upload File page. Here I define multiple file uploads.
 
<! ----------------------------------------- File name: Upload. jsp ---------------------------------->
 
<% @ Taglibprefix = "S" uri = "/Struts-tags" %>
 
<HTML>
 
<Head>
 
<Metahttp-equiv = "Content-Type" content = "text/html; charset = gb2312">
 
<Title> upload a file </title>
 
</Head>
 
<Body>
 
<! -- Upload file form definition -->
 
<S: formaction = "Upload" method = "Post" enctype = "multipart/form-Data">
 
<Tr>
 
<! -- Upload File tag definition -->
 
<TD> upload a file: <s: filename = "file"> </S: File> </TD>
 
</Tr>
 
<Tr>
 
<TD> upload a file again: <s: filename = "file"> </S: File> </TD>
 
</Tr>
 
<Tr>
 
<Tdalign = "Left"> <s: Submit name = "Submit" value = "Submit"> </S: Submit> </TD>
 
</Tr>
 
</S: Form>
 
</Body>
 
</Html>
 
Result page after the file is uploaded successfully
 
<! ----------------------------------------- File name: result. jsp ---------------------------------->
 
<% @ Taglibprefix = "S" uri = "/Struts-tags" %>
 
<HTML>
 
<Head>
 
<Metahttp-equiv = "Content-Type" content = "text/html; charset = gb2312">
 
<Title> upload result </title>
 
</Head>
 
<Body>
 
Upload files:
 
<! -- Display the uploaded file name -->
 
<S: propertyvalue = "filefilename"/>
 
</Body>
 
</Html>
 
Uploadaction code
 
<! ----------------------------------------- File name: uploadaction. Java ---------------------------------->
 
Import java. Io. file;
 
Importjava. Io. fileinputstream;
 
Importjava. Io. filenotfoundexception;
 
Importjava. Io. fileoutputstream;
 
Importjava. Io. ioexception;
 
Importjava. Io. inputstream;
 
Importjava. Io. outputstream;
 
Import java. util. List;
 

 
Importorg. Apache. struts2.servletactioncontext;
 
Importcom. opensymphony. xwork2.actionsupport;
 

 
// File Upload action
 
Public class uploadaction extends actionsupport {
 
// Upload File Storage path
 
Private Final Static stringuploaddir = "/upload ";
 
// Upload a file set
 
Private list <File> file;
 
// Upload a file name set
 
Private list <string> filefilename;
 
// A set of upload file content types
 
Private list <string> filecontenttype;
 

 
Public list <File> GetFile (){
 
Return file;
 
}
 

 
Public void setfile (list <File> file ){
 
This. File = file;
 
}
 

 
Public list <string> getfilefilename (){
 
Return filefilename;
 
}
 

 
Public void setfilefilename (list <string> filefilename ){
 
This. filefilename = filefilename;
 
}
 

 
Public list <string> getfilecontenttype (){
 
Return filecontenttype;
 
}
 

 
Public void setfilecontenttype (list <string> filecontenttype ){
 
This. filecontenttype = filecontenttype;
 
}
 

 
Public String execute () throws exception {
 
For (INT I = 0; I <file. Size (); I ++ ){
 
// Upload each object cyclically
 
Uploadfile (I );
 
}
 
Return "success ";
 
}
 

 
// Execute the upload function
 
Private void uploadfile (INTI) throws filenotfoundexception, ioexception {
 
Try {
 
Inputstreamin = newfileinputstream (file. Get (I ));
 
Stringdir = servletactioncontext. getrequest (). getrealpath (uploaddir );
 
Fileuploadfile = new file (Dir, this. getfilefilename (). Get (I ));
 
Outputstreamout = newfileoutputstream (uploadfile );
 
Byte [] buffer = new byte [1024*1024];
 
Int length;
 
While (length = in. Read (buffer)> 0 ){
 
Out. Write (buffer, 0, length );
 
}
 

 
In. Close ();
 
Out. Close ();
 
} Catch (filenotfoundexception ex ){
 
Ex. printstacktrace ();
 
} Catch (ioexception ex ){
 
Ex. printstacktrace ();
 
}
 
}
 
}
 
Configuration of file upload in the Struts. xml configuration file:
 
<! ----------------------------------------- File name: struts. xml ---------------------------------->
 
<Struts>
 
<! -- System constant definition, defining the encoding of the character set of the uploaded file -->
 
<Constantname = "struts. i18n. encoding" value = "gb2312"> </constant>
 
<! -- System constant definition, defining the temporary storage path of uploaded files -->
 
<Constantname = "struts. multipart. savedir" value = "C: \"> </constant>
 
<! -- Action package definition -->
 
<Packagename = "c04.4" extends = "struts-Default">
 
<! -- Action name, class, and navigation page definition -->
 
<! -- Define the action to be navigated through action class processing -->
 
<Actionname = "Upload" class = "Action. uploadaction">
 
<Resultname = "input">/JSP/upload. jsp </result>
 
<Resultname = "success">/JSP/result. jsp </result>
 
</Action>
 
</Package>
 
</Struts>
 
(1): file upload page 4.8.
 
Figure 4.8 File Upload
 
(2) Select File 4.9.
 
Figure 4.9 select an uploaded file
 
(3): Click the submit button and the file upload success page is displayed, as shown in Figure 4.10.
 
Figure 4.10 Effect of successful File Upload
 

 
Location of the uploaded file: the server used for this project is tomcat, which is under the root directory of this project in webapps of Tomcat. Find it for yourself and download the file from here.
 
Continue learning to download files tomorrow. Pai_^
 

 

 

 

 

 

 
Development of the struts2 file download function
Technical Points
The code in this section describes the development process of the file download function. The knowledge points are as follows:
 
= After the uploaded page is modified, the Code content can be downloaded from the file.
 
= Downloadaction file download function development.
 
= Configuration of downloadaction in struts. xml and download of files with a file name of Chinese characters.
 
= File download process display.
 
DEMO code
On the upload success page, I want to provide a "Download" link after each file is uploaded.
 
<! ----------------------------------------- File name: result. jsp ---------------------------------->
 
<% @ Taglibprefix = "S" uri = "/Struts-tags" %>
 
<Body>
 
Upload files:
 
<Table>
 
<! -- The uploaded file name is displayed cyclically -->
 
<S: iteratorvalue = "filefilename" status = "FN">
 
<Tr>
 
<TD>
 
<! -- Name of the uploaded file -->
 
<S: property/>
 
</TD>
 
<TD>
 
<! -- The download object URL is a defined download action -->
 
<! -- Download the file name as the filename value of The Link parameter, expressed in an ognl expression -->
 
<Ahref = "<s: URL value = 'download. action'>
 
<S: Param name = 'filename'
 
Value = 'filefilename [# fn. getindex ()] '/>
 
</S: URL> "> download </a>
 
</TD>
 
</Tr>
 
</S: iterator>
 
</Table>
 
</Body>
 
Downloadaction code
 
<! ----------------------------------------- File name: downloadaction. Java ---------------------------------->
 
Import java. Io. inputstream;
 
Import java. Io. unsupportedencodingexception;
 

 
Import org. Apache. struts2.servletactioncontext;
 
Import com. opensymphony. xwork2.actionsupport;
 

 
Public classdownloadaction extendsactionsupport {
 
// Original storage path of the downloaded file
 
Private Final Static string downloadfilepath = "/upload /";
 
// File name parameter variable
 
Private stringfilename;
 

 
Public stringgetfilename (){
 
Returnfilename;
 
}
 

 
Public void setfilename (string filename ){
 
This. filename = filename;
 
}
 

 
// Read the file output stream from the original storage path of the downloaded file
 
Public inputstreamgetdownloadfile (){
 
Return
 
Servletactioncontext. getservletcontext (). getresourceasstream (downloadfilepath + filename );
 
}
 
// If the downloaded file name is Chinese, convert the character encoding
 
Public stringgetdownloadchinesefilename (){
 
String downloadchinesefilename = filename;
 

 
Try {
 
Downloadchinesefilename = new string (downloadchinesefilename. getbytes (), "ISO8859-1 ");
 
} Catch (unsupportedencodingexception e ){
 
E. printstacktrace ();
 
}
 

 
Returndownloadchinesefilename;
 
}
 

 
Public stringexecute (){
 
Return success;
 
}
 
}
 
Configuration of File Download In the Struts. xml configuration file:
 
<! ----------------------------------------- File name: struts. xml ---------------------------------->
 
<Struts>
 
<! -- Define the action for downloading an object -->
 
<Action name = "Download" class = "Action. downloadaction">
 
<! -- Set the file name parameter, which is uploaded from the page -->
 
<Param name = "FILENAME"> </param>
 
<Result name = "success" type = "stream">
 
<! -- Download file type definition -->
 
<Paramname = "contenttype"> text/plain </param>
 
<! -- Solution for downloading files -->
 
<Paramname = "contentdisposition">
 
Attachment; filename = "$ {downloadchinesefilename }"
 
</Param>
 
<! -- Download file output stream definition -->
 
<Paramname = "inputname"> downloadfile </param>
 
</Result>
 
</Action>
 
</Struts>
 
(1): File Download start page 4.12.
 
Figure 4.12 File Download
 
(2): single-click Download link, as shown in Figure 5-6. download the file 1.txt on the right.
 
Figure 4.13 handling of downloaded files
 
(3) Click "save" and select the path for storing the downloaded file, as shown in Figure 4.14.
 
Figure 4.14 select a storage path for the downloaded file
 
Code explanation
(1) In result. jsp, the "filefilename" loop display and link are defined through the iterator tag and URL tag. I will introduce the "status" and ognl expressions in the following sections. Here, I will show you how to use tags to display the content shown in Figure 4.12. Note that the <param> label defines a parameter for downloadaction, which is named "FILENAME", because in section 4.4.1, the "filefilename" defined by the author is a list-type data set, therefore, the ognl expression is used to pass the file name into the downloadaction as the "FILENAME" parameter value.
 
(2) The downloadaction file first defines the constant downloadfilepath, which is the path name of the downloaded file stored on the server, that is, the path name uploaded to the file on the server in section 4.4.1.
 
After downloadfilepath is defined, attribute variables of downloadaction are defined. Because the parameter "FILENAME" is defined in result. jsp, it is used as the downloadaction attribute variable and the corresponding getter and setter methods need to be defined.
 
Then, the getdownloadfile method is defined. It returns a file stream, which indicates converting the downloaded file into an output stream for convenient download. Use the "servletactioncontext" API provided by struts2 to take the path of the downloaded file as a method parameter, read the downloaded file, and convert it into a file stream.
 
There is also a getdownloadchinesefilename method, which is mainly used to convert the character encoding set of a file with a file name of Chinese characters. In the web system, the variable values passed in by views such as JSP pages, especially Chinese characters. The default character encoding set is "ISO8859-1", so the Java string class API is used to convert character encoding into the character encoding set required by development. Prevents Chinese Character garbled characters.
 
(3) struts. xml defines the action named "Download. Its own parameter "FILENAME" is defined here because its value is uploaded from the JSP page, and no value is assigned to it.
 
The Type attribute is defined in the <result> label and the value is "stream ". For the development of the download file function, downloadaction must set the type attribute and the value is "stream ". This is because the xml configuration file that comes with struts2 has a definition of the "stream" result return type for the struts-default.xml, the Code is as follows:
 
<! ----------------------------------------- File name: struts-default.xml -------------------------------->
 
<Result-typename = "stream" class = "org. Apache. struts2.dispatcher. streamresult"/>
 
Here, struts2 defines the result return type as "stream", which is mainly used to process the input and output streams of files. Because the download file is to convert the file into an input and output stream, and put it from one file path to another file path. Therefore, you must set this result type.
 
"Contenttype", "contentdisposition", and "inputname" are all attributes of the result. "Contenttype" is the file type. Because the downloaded file is a text file, the value is set to the text file type. For details about how to define the file types, see section 4.4.1. "Contentdisposition" indicates the processing method for downloading files, and "4.13" indicates the processing method. Note that if the value defined in "contentdisposition" removes the previous "attachment", the download method is not as an attachment. If you click the "Download" link, the downloaded file is displayed in the browser. You can try it out. There is a "$ {downloadchinesefilename}", which is the purpose of defining the getdownloadchinesefilename method in downloadaction. $ {downloadchinesefilename} is the ognl expression, it displays the specific value of the "downloadchinesefilename" variable, because the getdownloadchinesefilename method is defined in downloadaction, the downloaded file name that has been converted to the desired character set as the name displayed in the "download file" Mode dialog box does not cause any garbled characters. "Inputname" is the most critical attribute and must be defined. The value "downloadfile" defined in the "inputname" parameter is the name of the file stream returned by the getdownloadfile method in downloadaction. In struts2, acion uses the get method with the prefix to obtain the values of various attributes, some of which are defined in action, some are like using ognl expressions or directly defining in the configuration file in this example.
 
(4) start to display the file download function. Follow the steps described above. The author uploads two text files and downloads the files on the upload success page. In Figure 4.13, click the "save" button to display figure 4.14. Select the path to store the downloaded file on the local machine to complete the download.

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.