Java STRUTS2 Implementation of simple file upload and download _java

Source: Internet
Author: User

First, Struts2 file upload
Struts2 File Upload implementation is very simple, only a few steps can be completed;
Note:
(1) file Upload struts2 tag: <s:file name= "" label= "Upload"/>
(2) File upload premise is the form attribute method= "POST" enctype= "Multipart/form-data";
(3) Web applications must contain Common-fileupload.jar and Common-io.jar, because the struts2 default upload parser uses is Jakarta;
(4) The maximum allowable file size can be configured in Struts.xml: <constant name= "struts.multipart.maxSize" value= "..."/> the default is 2M;

1. normal File Upload
To implement the rule:
(1) Set the form control in the JSP <s:file name= "upload" label= "Upload"/>
(2) Defining attributes in action:
Private File upload; Include file contents
Private String Uploadfilename; The name of the uploaded file;
Private String Uploadcontenttype; The MIME type of the uploaded file;
These properties will be automatically assigned as the file is uploaded;
(3) Completing the Write disk function in execute ();

code example:
Upload01action.java

Package org.upload.action; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
 
Import Java.io.FileOutputStream; 
 
Import Org.apache.struts2.ServletActionContext; 
 
Import Com.opensymphony.xwork2.ActionSupport; 
  public class Upload01action extends Actionsupport {private File upload; 
  Private String Uploadfilename; 
  Private String Uploadcontenttype; 
  private String name; public string Execute () throws exception{string path = Servletactioncontext.getservletcontext (). Getrealpath ("/web-inf 
    /upload "); 
    String filename = path+file.separator+name; 
    FileInputStream in = new FileInputStream (upload); 
    FileOutputStream out = new FileOutputStream (filename); 
    Byte[]b = new byte[1024]; 
    int len = 0; 
    while ((Len=in.read (b)) >0) {out.write (B,0,len); 
    } out.close (); 
  return SUCCESS; 
  Public File Getupload () {return upload; 
  The public void Setupload (File upload) {this.upload = upload; } public String Getuploadfilename () {return uploadfilename; 
  } public void Setuploadfilename (String uploadfilename) {this.uploadfilename = Uploadfilename; 
  Public String Getuploadcontenttype () {return uploadcontenttype; 
  } public void Setuploadcontenttype (String uploadcontenttype) {this.uploadcontenttype = Uploadcontenttype; 
  Public String GetName () {return name; 
  public void SetName (String name) {this.name = name;  } 
   
   
}

Struts.xml

 <?xml version= "1.0" encoding= "UTF-8"?> <! 
DOCTYPE struts public 
  "-//apache Software foundation//dtd struts Configuration 2.0//en" 
  "http:// Struts.apache.org/dtds/struts-2.0.dtd "> 
 
<struts> 
  <constant name=" Struts.devmode "value=" true "/> 
  <constant name=" struts.custom.i18n.resources "value=" message "></constant> 
  <package Name= "Default" namespace= "/" extends= "Struts-default" > <action name= "upload0*" class= " 
    Org.upload.action.upload0{1}action "> 
      <param name=" name ">1.jpg</param> 
      <result>/{1 }.jsp</result> 
    </action> 
  </package> 
</struts> 

1.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% 
@taglib prefix= "s" uri= "/ Struts-tags "%> 
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 
 
 

2. Use Interceptor to filter
The manual implementation of the filtering method is very simple, that is, the use of input to check the way to filter, that is, in the Validate () filter;
And here to talk about the Interceptor mode is a good way, only need to configure in the configuration file, flexibility is good, can limit the type of file, file size, if the uploaded file does not meet the requirements, then return the input logic view;

To configure the Interceptor step:

(1) File upload interceptor for fileupload;
(2) The allowedtypes and maximumsize of the given parameters are required;
(3) After the FileUpload interceptor, you need to add <interceptor-ref name= "Defaultstack"/>

code example:
Because filtering through interceptors requires only configuration of Struts.xml, only the Struts.xml configuration is given here

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache.org/dt Ds/struts-2.0.dtd "> <struts> <constant name=" Struts.devmode "value=" true "/> <constant" St Ruts.custom.i18n.resources "value=" message "></constant> <package name=" Default "namespace="/"extends=" Struts-default "> <action name=" upload0* "class=" org.upload.action.upload0{1}action "> <interceptor- Ref name= "FileUpload" > <param name= "allowedtypes" >image/jpeg,image/gif</param> <param Name= "MaximumSize" >1024*1024</param> </interceptor-ref> <interceptor-ref name= "Defaultstac K "></interceptor-ref> <param name=" name ">1.jpg</param> <result>/{1}.jsp</resul t> <result name= "input" >/{1}.jsp</result> </action> </packAge> </struts>  

We also need the error message after the configuration file upload failed, we need to configure in the global internationalized resource file:

struts.messages.error.content.type.not.allowed= file type mismatch 
 
struts.messages.error.file.too.large= file is too large 

Second, Struts2 file download
We are learning the servlet and HTTP protocol can be implemented to download the file, that is, write Content-disposition header can be the implementation of the principle of struts2 is this, but provides a better encapsulation;
Struts2 Stream result types are specifically used to implement file downloads;
(1) Configure stream result type in Struts.xml, and configure ContentType, contentdisposition, buffersize parameters, Template:

<action name= "Download" class= "" > 
  <result type= "stream" Name= "Success" > 
    <param name= " ContentType "></param> 
    <param name=" contentdisposition ">attachment;filename=" "</param> 
    <param name= "buffersize" >4096</param> 
  </result> 
</action> 

(2) Create the public InputStream getInputStream () throws Exception in action, which is used to obtain the input stream of the downloaded file;

Downloadaction.java

Package org.download.action; 
 
Import Java.io.InputStream; 
 
Import Org.apache.struts2.ServletActionContext; 
 
Import Com.opensymphony.xwork2.ActionSupport; 
 
public class Downloadaction extends Actionsupport {public 
  inputstream getInputStream () 
     
    throws Return Servletactioncontext.getservletcontext (). getResourceAsStream ("/web-inf/upload/1.jpg"); 
     
  } 
  Public String Execute () throws exception{return 
    SUCCESS 
  } 
} 

Struts.xml

<action name= "Download" class= "org.download.action.DownloadAction" > 
      <result type= "stream" name= " Success "> 
        <param name=" ContentType ">image/jpeg</param> 
        <param name=" contentdisposition ">attachment;filename=" 1.jpg "</param> 
        <param name=" buffersize ">4096</param> 
      </ Result> 
    </action> 

To complete the download.

Java struts2 File upload the implementation of the download for everyone to introduce here, thank you for your reading.

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.