struts1.3--File Upload and download

Source: Internet
Author: User

1.Struts File Upload

In web development, it often involves uploading and downloading files, for example, when registering an account, we need to upload our own avatar and so on.
We can make it easy to upload files using struts.

1.1 Development Steps

Now, let's say we're going to upload our avatar at the time of registration. The new project name is Strutsfileupanddown and introduces Struts1.3

(1) First, write the registered JSP page register.jsp
Its body content is as follows:

<Body><H1> Registered Users</H1><%--If the form has a file control, you need to re-specify how the form is encoded--%><FormEnctype="Multipart/form-data"action="/strutsfileupanddown/register.do"Method="POST" > Name:<input type= "text" name=" name "/>< Br> head: <input type= "file" name= "photo"/> <br> < Input type= "submit" value=< Span class= "Hljs-value" > "register"/> </form> </BODY>          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • Here you use normal HTML tags to write the form. Be sure to add the Enctype property of the form, and the content is "Multipart/form-data"
    • This must be committed using the Post method, and the Get method will be faulted
    • The address of the action can be empty at the beginning, after the action, then fill up. Here my action's path is "/register"

(2) Add the corresponding actionform, the name is UserForm

PublicClassuserform extends ActionForm {private String name = null; private formfile photo = null; public String getname () {return Name } public void setName (String name) { this.name = name;} public formfile getphoto () {return Photo } public void setPhoto (FormFile Photo) {this.photo = Photo;}}          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • To be sure, the file control in the JSP corresponds to the Formfile object, which is provided by the struts framework.

(2) Add the corresponding action, name registeraction, and configure path /register to
The most important thing is how the action is written, and when we click Register, it is the action that handles the logic, and the file is passed through this action.

    • First we want to get the content in UserForm:
UserForm userForm = (UserForm) form;String username = userForm.getName();FormFile formFile = userForm.getPhoto();
    • 1
    • 2
    • 3
    • Next, we save the file, the Formfile object has the getInputStream () method to get the input stream of the file. At this point we also need an output stream outputstream, which is used to save the input stream to the server's disk through the output stream. Note, however, that the output path of the output stream is the absolute path under Tomcat
File name String fileName = Formfile.getfilename ();Gets the input stream InputStream is = Formfile.getinputstream ();//get an output stream //first get the absolute path after uploading the file folder to the tomcat server string path = Request.getservletcontext (). Getrealpath ( "file"); OutputStream OS = new fileoutputstream (path +  "\ \" + fileName); //read the file and write it out to the server file folder int len = 0;//do a cache byte[" bytes = new byte[1024]; Loop processing while (len = is.read (bytes)) > 0) {//read a little, write a little Os.write (bytes, 0, Len);}       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

Of course, this whole process has to deal with exceptions. If it doesn't go wrong, we can pass the file on to the server.

"Note that some simple configuration steps are omitted here."

1.2 Improvements

(1) Problem 1: Chinese garbled processing, if the user upload the file is Chinese name will appear garbled

At this point, the filter can be a good solution to this problem. Just add a filter and set the request's encoding to Utf-8.

Publicclass encodingfilter implements Span class= "Hljs-title" >filter { @Override public void destroy () {}  @Override public void dofilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2) throws IOException, Servletexception { Arg0.setcharacterencoding ( @Override public void init (filterconfig arg0) throws servletexception {}}    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

The configuration is as follows:

<Filter><filter-name>encodingfilter</< Span class= "Hljs-title" >filter-name> <filter-class> Com.gavin.filter.encodingfilter</filter-class></filter>< filter-mapping> <filter-name>encodingfilter</filter-name> < Url-pattern>/*</url-pattern> </FILTER-MAPPING>         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

(2) Question 2: Here we save the file name of the server is the user upload name, then if there are two users upload the same file name will be overwritten, so we will be on the server side of the file name processing

Here, we no longer use the name of the user-uploaded file. So what can you do to ensure that the file name is unique?

    • 1. One method is to use the current time (year + month + day + time + minutes + seconds + milliseconds) as the name of the file
    • 2. In addition, the Java.util.UUID class can be used directly, the UUID is not repeated, this method is the simplest.
String uuid = UUID.randomUUID().toString();
    • 1
    • 3. Of course, after using the UUID, but also to add the original file suffix, so simply write a tool class:
public Span class= "Hljs-class" >class mytools {/** * get file suffix * @param fileName * @return */ Span class= "Hljs-keyword" >public static String getFileSuffix ( String fileName) {return filename.substring (Filename.lastindexof ( /** * get uuid * @return */ Public static string getuuid () {String uuid = Uuid.randomuuid (). ToString (); return uuid;}            
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

(3) Question 3: What if the user uploads not the picture? What if a user uploads a picture that is too large?

So here we have to file restrictions, to the type and size of the file limit, if not meet the requirements, then jump to an error page and give a hint:
Here I limit the file size limit to 10MB, as follows:

if (fileSize > 10 * 1024 * 1024) {    request.setAttribute("error", "文件大小不能超过10MB!"); return mapping.findForward("error");}if(!formFile.getContentType().startsWith("image/")){ request.setAttribute("error", "文件格式有错,请检查!"); return mapping.findForward("error");}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

"Note" The type of file is not a picture, not by the suffix name to determine, to invoke the Formfile method, the specific file type you can view the Tomcat installation directory under the Conf folder in the Web. xml file configuration.

So, finally, a complete registeraction is this:

PublicClassRegisteractionExtendsAction {Public ActionforwardExecute (actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse response) {UserForm UserForm = (userForm) Form; String username = userform.getname (); Formfile formfile = Userform.getphoto ();Through Formfile we can obtain various information about the user uploading files, such as size, name, etc. String fileName = Formfile.getfilename ();int fileSize = Formfile.getfilesize ();if (FileSize >10 *1024 *1024x768) {Request.setattribute ("Error","File size cannot exceed 10mb!");Return Mapping.findforward ("Error"); }if (!formfile.getcontenttype (). StartsWith ("image/")) {Request.setattribute ("Error","File format is wrong, please check!");Return Mapping.findforward ("Error"); } InputStream is =Null OutputStream OS =Null String uuid = Mytools.getuuid (); String suffix = mytools.getfilesuffix (fileName); String newfilename = uuid + suffix;try {is = Formfile.getinputstream (); String path = Request.getservletcontext (). Getrealpath ("File"); SYSTEM.OUT.PRINTLN (path); OS =New FileOutputStream (Path +"\ \" + NewFileName);int len =0;byte[] bytes =Newbyte[1024]; while (len = is.read (bytes)) > 0) {os.write (bytes, 0, Len); } //here omitted to save the operation of the database //logical normal Jump, also omitted} catch (Exception e) {e.printstacktrace ();} finally {try {if (OS = null) {os.close ();} if (is! = null) {is.close ();}} catch (Exception E2) {e2.printstacktrace ();}} Request.setattribute ( "error",  "Registration Error! "); return mapping.findforward ( "error");}}     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
2.Struts File Download

File download, we have introduced the native Servlet, we can refer to the "servlet--use HTTP response header content-disposition download file example."

Of course, when we wrote the downloaded business logic in a servlet, there was nothing different here, except that we were going to write the business logic in a struts action, and that action did not need to be configured with the appropriate form.

When we click on the downloaded hyperlink, let it request this action. And finally let the action jump to the original page:

return mapping.findForward("goback");
    • 1

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

struts1.3--File Upload and 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.