Javaweb file upload and download function in-depth analysis (ii) _java

Source: Internet
Author: User

Followed by a narrative:

Second, file upload and download

STRUTS2 Development of Sanbang, page jsp-configuration file struts2.xml--and action-class action

File Upload premise:
Method of form form must be post
The enctype of form form must be multipart/form-data
Provides an upload entry field for type= "file"

Some rules for Struts support for file uploads

1. Single File Upload

Development steps:

1), under the Web-inf/lib to join Commons-fileupload-1.2.1.jar, Commons-io-1.3.2.jar. These two files can be downloaded from http://commons.apache.org/

2, the second step: Write upfile.jsp, the form table enctype set to: "Multipart/form-data", as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib uri=
"/struts-tags" Prefix= "s"%>
<body>
  <s:actionerror/>
   
 

Write error page error.jsp

 <body>
  server busy, try again later.
 </body>

success.jsp

 <body>
  upload Success
 </body>

3, Write UploadAction1 class: Add properties to the action class, attributes correspond to the names of the file fields in the form:

Package com.itheima.actions;
Import Java.io.File;

Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;

Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
  File Upload: FileUpload Interceptor completes the public class UploadAction1 extends Actionsupport {private String username; The private File photo;//and the form's upload field names are consistent.
  Type is a file type private string photofilename;//the file name that was uploaded private string photocontenttype;//MIME type//ellipsis getter and setter method for uploading files
    Public String upload () {System.out.println (photofilename+ ":" +photocontenttype);
    Normal field: System.out.println (username); Upload field: Upload to a folder.
    Save to the applied images directory String Realpath = Servletactioncontext.getservletcontext (). Getrealpath ("/images");
    File directory = new file (Realpath);
    if (!directory.exists ()) {directory.mkdirs ();
      try {fileutils.copyfile (photo, new File (directory, photofilename));
    return SUCCESS;
      catch (IOException e) {e.printstacktrace (); ReTurn ERROR;

 }

  }
}

Add the following configuration in the Struts.xml file

<action name= "Upload1" class= "Com.itheima.actions.UploadAction1" method= "Upload" >
  <interceptor-ref Name= "Defaultstack" >
    <param name= "Fileupload.allowedtypes" >image/jpeg,image/png</param>
    <param name= "Fileupload.allowedextensionsset" >jpg,jpeg,png</param>
  </interceptor-ref>
  <result>/success.jsp</result>
  <result name= "error" >/error.jsp</result>
  <result name= "Input" >/index.jsp</result>
</action>

Principle Analysis:

A, the FileUpload interceptor is responsible for handling file upload operations, it is the default Defaultstack interceptor stack of a member. The Interceptor has 3 properties to set.
maximumsize: The maximum length of the uploaded file (in bytes), with a default value of 2 MB
allowedtypes: Types of files allowed to be uploaded, comma-delimited between types
allowedextensions: Allow file extensions to be uploaded, separated by commas between extension names
You can overwrite these 3 properties in the Struts.xml file

b, out of size or illegal file upload, will be an error (turn to an input view)

Pass:
<s:actionError/> <s:feildError/> tips for displaying error messages

C, error message prompt to Chinese version: With the internationalization of the message resource file

If the error is caused by configuring global default parameters, it is best to use the global message resource file.
STRUTS2 the default hint resource file: Struts2-core-**.jar's org.apache.struts2 struts-message.properties file. Override the key value to overwrite the corresponding value.

The configuration is as follows:

Struts.messages.error.uploading=error uploading: {0}
Struts.messages.error.file.too.large=file too large: {0} ' {1} ' ' {2} ' {3}
Struts.messages.error.content.type.not.allowed=content-type not allowed: {0} ' {1} ' ' {2} ' {3}
Struts.messages.error.file.extension.not.allowed=file extension not allowed: {0} ' {1} ' ' {2} ' {3}

{0}:<input type= The value of the Name property in the ' file ' name= ' Uploadimage ' >
{1}: The true name of the uploaded file
{2}: The name of the upload file saved to the temp directory
{3}: The type of upload file (for Struts.messages.error.file.too.large is the size of the uploaded file)

Source:

Modify information for a resource file that displays an error

Step One: create a new resource file such as fileuploadmessage.properties, placed under SRC
Add the following information to the resource file
struts.messages.error.uploading= upload error: {0}
struts.messages.error.file.too.large= upload file is too large: {0} ' {1} ' ' {2} ' {3}
struts.messages.error.content.type.not.allowed= upload file type not allowed: {0} ' {1} ' ' {2} ' {3}
struts.messages.error.file.extension.not.allowed= upload file suffix name not allowed: {0} ' {1} ' ' {2} ' {3}

Step Two: load the resource file in the Struts.xml file

<!--resource file to configure error messages for uploaded files-->
<constant name= "struts.custom.i18n.resources" value= "Cn....xxx.fileuploadmessage"/>

2, multiple file upload

Upload multiple files, you can use the array or list, other and single file upload similar.

Package com.itheima.actions;
Import Java.io.File;

Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;

Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
  File Upload: FileUpload Interceptor completes the public class UploadAction2 extends Actionsupport {private String username; Private file[] photo;//is consistent with the form's upload field name. Type is a file type. Array or list private string[] photofilename;//uploaded file name private string[] photocontenttype;//MIME type of uploaded file public String upload () {//upload field: Upload to a folder.
    Save to the applied images directory String Realpath = Servletactioncontext.getservletcontext (). Getrealpath ("/images");
    File directory = new file (Realpath);
    if (!directory.exists ()) {directory.mkdirs (); try {for (int i=0;i<photo.length;i++) {fileutils.copyfile (photo[i], new File (directory, Photofilena
      Me[i]));
    return SUCCESS;
      catch (IOException e) {e.printstacktrace ();
    return ERROR;

 }

  }
}

3, File download

Principle: Struts2 provides the stream result type, which is specifically used to support file download functions.
Specifies that the stream result type needs to specify an inputname parameter that specifies an input stream that provides the entry of the downloaded file

Encoding Step:
1), Action class Downloadaction:

Package com.itheima.actions;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.InputStream;

Import Java.net.URLEncoder;
Import Org.apache.commons.io.FilenameUtils;

Import Org.apache.struts2.ServletActionContext;

Import Com.opensymphony.xwork2.ActionSupport;
  public class Downloadaction extends Actionsupport {private InputStream image;//file name with the problem private String filename;//
  Private long filesize;
  Public InputStream GetImage () {return image;
  public void SetImage (InputStream image) {this.image = image;
  Public String GetFileName () {return filename;
  Public long GetFileSize () {return filesize; The public string download () throws exception{//gives the image byte stream a string filerealpath = Servletactioncontext.getservle
    Tcontext (). Getrealpath ("/web-inf/classes/. jpg");
    filename = Filenameutils.getname (Filerealpath); Mode one: Chinese files to be URL coded//filename = Urlencoder.encode (filename, "UTF-8 ");
    FileSize = new File (filerealpath). Length ();
    SYSTEM.OUT.PRINTLN (filename);
    Image = new FileInputStream (Filerealpath);
  return SUCCESS;

 }
}

Struts.xml configuration file: Configuring the results of the stream type primarily

<struts> <constant name= "Struts.devmode" value= "true"/> <constant "name=" Daccess "value=" true "/> <action name=" Download "class=" com.itheima.actions.DownloadAction "method=" Download "&
      Gt <result type= "Stream" > <param name= "inputname" >image</param><!--the name of the InputStream field in the action class, which is required in the Actio N provides Gettargetfile method, returns inputstream--> <param name= "ContentType" >application/octet-stream</param>& lt;! --Tell the browser the response header, the MIME format of the file, invoke the getContentType method in the action--> <!--use the OGNL expression in Struts.xml to get the value of the property in the action class. Invokes the GetFileName ()--> <!--Chinese file name encoding in the Action class: mode two. Using OGNL expressions, calling UrlEncode static method--> <!--default Ognl calling static methods is not possible. , you need to turn on a constant switch. struts.ognl.allowstaticmethodaccess=true--> <param name= "Contentdisposition" >attachment;fil ename=${@java. Net.urlencoder@encode (filename, ' UTF-8 ')}</param><!--tells the browser how to download--> <param name= "cont Entlength "&GT;${FILESIZE}&LT;/PARAM&GT

 </result> </action> </package> </struts>

Interceptor and file upload is written here, very tired, but a full sense of achievement.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.