1. Struts2 file upload requires Apache's commons-io-version. Jar and commons-fileupload-version. Jar two jar packages.
2. In the pageThe <s:file name= "Example"/> tag will look for and execute three setter methods in the corresponding action class:setexample, Setexamplefilename and setexamplecontenttype. Where the setexamplefilename method assigns the file name of the user's uploaded file (String, excluding file path) to the corresponding property of the action class,setexamplecontenttype the method corresponds to the MIME type (String) of the uploaded file, such as "Text/plain".
3. The most important process for uploading files is to complete a copy of the file, by using the file byte output stream to write the files uploaded by the user to a directory.
4. Struts2 upload files need to useFileUpload Interceptor, this interceptor is included in theDefaultstack Interceptor Stack, the corresponding interceptor class isOrg.apache.struts2.interceptor.FileUploadInterceptor。 The interceptor has three common properties:MaximumSize, allowedextensions and allowedtypes, respectively, represent the maximum allowable size of the uploaded file, allowing the file suffix name to be uploaded and the file MIME type to be uploaded. Multiple items are separated by commas.
Note: After you manually configure the FileUpload interceptor in the <interceptor-ref> element, do not forget to add the Defaultstack interceptor stack shortly thereafter, because the Defaultstack interceptor stack will not be automatically referenced by the container at this time. Must be manually added on.
5.Struts.multipart.saveDirUsed to specify the folder where temporary files are stored, which is written in thestruts.propertiesFile. can useStruts.xmlIn the fileconstantelement to override the default location, such as
<constant name="struts.multipart.saveDir" value="c \" ></ Constant>
The above line of code specifies that the C packing directory is a temporary folder.
6. By rewriting the struts.messages.error.content.type.not.allowed key in the International resource file and The Struts.messages.error.file.too.large key corresponds to a value that implements the custom error message. Cases:
Struts.xml file:
<!--use the constant element in the Struts.xml file to specify a custom error message in the global message.properties file--><constant name=" Struts.custom.i18n.resources" value="message"></constant>
Message.properties file:
<!--theprompt when the custom upload file type is not allowed--is atry<!--the message when the custom upload file is too large-- is Try again
Note: The message.properties file should be located in the Web-inf/classes directory.
7. When uploading multiple files, struts automatically fills in the information in the File Upload page form, as long as the properties in the relevant action class become array types or list types. Note, however, that the name of multiple file tags in a form must be the same. If the upload page is as follows:
<!--when uploading multiple files, the Name property of the file tag must match-file1:<s:file name="file"> File2:<s:file name="file">file3:<s:file name=" File">
The corresponding action class is as follows:
// the corresponding action class when uploading multiple files Public class Uploadaction extends Actionsupport { private list<file> File; ....}
Struts automatically puts the uploaded three files into the member variable file of the action class, because the name property of the three file tags in the upload page is file!
8. The file download in struts is very convenient, just write a corresponding action, provide a method to return the InputStream stream, the input stream represents the portal of the downloaded file, this method is used to provide the input stream of the downloaded data, meaning is read from this stream, Then write to the browser for download. This method is written by the developer and requires only a return value of InputStream.
9. The result type of the file download is stream, and the corresponding class isOrg.apache.struts2.dispatcher.StreamResult。 The result type has three common properties:ContentType,contentdispositionAndInputName。
ContentTypeRepresents the MIME type of the downloaded file, which defaults toText/plain。
contentdispositionIndicates how the download file is processed, withinline(default) andAttachmentTwo kinds. If specified asinlinemode, the browser will first try to open the file directly, not directly open the Save dialog box;Attachmentmode directly pops up the File Save dialog box. The syntax format is:<param>attachment;filename= "Example.txt" </param>. At this point, regardless of the server side really downloaded the name of the file, the File Save dialog box displays the filename is example.txt.
InputName indicates the source stream of the downloaded file. If the inputname value is downloadFile, you must have a return type of InputStream in the corresponding action class Getdownloadfile method to return the downloaded file entry, refer to 8th.
Result Configuration instance:
<result name="Success"Type="Stream"> <param name="ContentType">text/plain</param> <param name="contentdisposition">attachment;filename="Example.txt"</param> <param name="InputName">downloadfile</param></result><em><span style="font-size:10pt; color: #0000ff;"><br></span></em>
10. If the file type is unknown, or if there is a file that the browser cannot open, such as a. Bean file, or if this action is used to do a dynamic file download, without prior knowledge of what the future file type is, then we can The value of ContentType is set to:application/octet-stream;charset=iso8859-1 , be sure to join CharSet, Otherwise, there will be some errors in the downloaded file; some people say at this time can also be set to become Application/x-download, according to the author's practice, the head can also work normally, however, the browser can not recognize the problem.
11. The file name contains the Chinese processing method:
Usestring NAMEINCN = String ("struts2 Chinese. txt". GetBytes (), "iso8859-1");Way to convert struts2 Chinese. txt to a browser-supported string NAMEINCN, and then place the string in the<param>attachment;filename= "..." </param>Jung-gu will be all right.
The specific operation method can refer to this article: implementation of the file download in Struts 2 (fix Chinese problem)
Having mastered this principle, it is not difficult to put forward some of the more simple methods described in the previous article. Here's a way I think of myself:
First, it is still necessary to add a member variable of type string in the corresponding action class to represent the file name that needs to be displayed, which may be named FILENAMEINCN. Then don't forget to generate its setter and getter methods.
Secondly When configuring the appropriate action in the Struts.xml file, pass a parameter to the action specifying the file name that you want to display to the customer, and of course, this file name can contain Chinese, and the next thing we do is to make some changes to the file name that contains the Chinese so that the browser can display it. We're in the association. The specified file name is "Chinese. txt" For specific configuration please refer to the code below.
Next, modify the action class in theSETFILENAMEINCNmethod, in this method, we use the methods mentioned above to convert the file name from the configuration file containing Chinese into a string that the browser can recognize.
Finally, in the result element of the configuration file, set theThe contentdisposition property is attachment;filename= "${FILENAMEINCN}" .
All right, it's done! Now the user in the download file, see is no longer a pair of garbled, but "Chinese. txt". Here are some of the code covered above.
The action is configured in the struts.xml file, where the action is named download:
<action name="Download" class="com.test.action.DownloadAction"> <param name="FILENAMEINCN"> Chinese .txt</param> <result name="Success"Type="Stream"> <param name="ContentType">text/plain</param> <param name="contentdisposition">attachment;filename="${FILENAMEINCN}"</param> <param name="InputName">downloadFile</param> </result></action>
The following is the corresponding downloadactioN class, where we can see that the downloaded file is actually a bls.txt file in the server-side WEBROOT/ABC directory, but because we specified in the action configuration that the file name is "Chinese. txt" and do the corresponding processing, so the user in the download time to see the filename is "Chinese. txt", instead of Bls.txt, refer to the 9th.
import java.io.InputStream; Import Com.opensymphony.xwork2.actionsupport;import Org.apache.struts2.ServletActionContext; Public classDownloadaction extends Actionsupport {PrivateString FILENAMEINCN; PublicString GETFILENAMEINCN () {returnFILENAMEINCN; } Public voidSETFILENAMEINCN (String filenameincn) {Try { This. FILENAMEINCN =NewString (Filenameincn.getbytes (),"iso-8859-1"); } Catch(Exception e) {e.printstacktrace (); } } PublicInputStream Getdownloadfile () {returnServletactioncontext.getservletcontext (). getResourceAsStream ("/upload/bls.txt"); } @Override PublicString Execute () throws Exception {returnSUCCESS; }}
Uploading and downloading of Struts2 files