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--%>    <form enctype="Multipart/form-data" action="/strutsfileupanddown/ Register.do " method=" POST ">Name:<input type="text" name="name" /><br>Avatar:<input type="file" name="Photo" /><br>         <input type="Submit" value="register" />    </form></body>
    • 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

 Public  class UserForm extends actionform {    PrivateString name =NULL;PrivateFormfile photo =NULL; PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicFormfileGetphoto() {returnPhoto } Public void Setphoto(Formfile photo) { This. Photo = photo; }}
    • 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();
    • 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 nameString fileName = Formfile.getfilename ();//Get input streamInputStream is = Formfile.getinputstream ();//Get an output stream//First get the absolute path after uploading the file folder to the Tomcat serverString path = Request.getservletcontext (). Getrealpath ("File"); OutputStream OS =NewFileOutputStream (path +"\\"+ FileName);//Read the file and write it out to the server file folderintLen =0;//Make a cachebyte[] bytes =New byte[1024x768];//Cycle processing while(len = is.read (bytes)) >0) {//Read a little, write a littleOs.write (Bytes,0, Len);}

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.

 Public  class encodingfilter implements Filter {    @Override     Public void Destroy() {    }@Override     Public void DoFilter(ServletRequest arg0, Servletresponse arg1, Filterchain arg2)throwsIOException, servletexception {arg0.setcharacterencoding ("Utf-8");    Arg2.dofilter (arg0, arg1); }@Override     Public void Init(Filterconfig arg0)throwsServletexception {}}

The configuration is as follows:

<filter>    <filter-name>Encodingfilter</filter-name>    <filter-class>Com.gavin.filter.EncodingFilter</filter-class></filter><filter-mapping>    <filter-name>Encodingfilter</filter-name>    <url-pattern>/*</url-pattern></filter-mapping>

(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();
    • 3. Of course, after using the UUID, but also to add the original file suffix, so simply write a tool class:
 Public  class mytools {    /** * Get file suffix * @param fileName * @return  */     Public StaticStringGetfilesuffix(String fileName) {returnFilename.substring (Filename.lastindexof (".")); }/** * Get UUID * @return  * *     Public StaticStringGetuuid() {String uuid = Uuid.randomuuid (). toString ();returnUuid }}

(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:

if1010241024) {    request.setAttribute("error""文件大小不能超过10MB!");    return mapping.findForward("error");}if(!formFile.getContentType().startsWith("image/")){    request.setAttribute("error""文件格式有错,请检查!");    return mapping.findForward("error");}

"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:

 Public  class registeraction extends Action {     PublicActionforwardExecute(actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse response)        {UserForm UserForm = (UserForm) Form;        String username = userform.getname (); Formfile formfile = Userform.getphoto ();//Through formfile we can get all kinds of information about user uploading files, such as size, name, etc.String fileName = Formfile.getfilename ();intFileSize = Formfile.getfilesize ();if(FileSize >Ten*1024x768*1024x768) {Request.setattribute ("Error","File size cannot exceed 10mb!");returnMapping.findforward ("Error"); }if(!formfile.getcontenttype (). StartsWith ("image/") {Request.setattribute ("Error","The file format is wrong, please check!");returnMapping.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 =NewFileOutputStream (path +"\\"+ NewFileName);intLen =0;byte[] bytes =New byte[1024x768]; while(len = is.read (bytes)) >0) {os.write (bytes,0, Len); }//Omit the operation to save the database here            //Logical normal jump, also omitted here}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!" ");returnMapping.findforward ("Error"); }}
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");

struts1.3--File Upload and download

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.