Javaweb struts2 Implementation of File upload download function Example Analysis _java

Source: Internet
Author: User
Tags file upload tomcat

In the B/s system, usually involves uploading files and downloading files, before the STRUTS2 framework, we are using Apache Commons sub-project FileUpload components to upload files, but in that case, the code looks more cumbersome, and not flexible , after learning the struts2, struts2 for file upload download provides a better implementation mechanism, where I separately upload a single file and multiple file upload source code to explain, here need to import file download upload two jar files, One is Commons-fileupload-1.2.2.jar, the other is Commons-io-2.0.1.jar.

Struts2 Single File Upload:

First is a JSP file upload page, this is relatively simple, is a form, which has a file upload box

  <!--in the file upload, form submission must be the way to post, because the file upload when the binary file may be very large, there is enctype attribute, this attribute must be written multipart/form-data,
Otherwise it will be uploaded to the server side in binary text--> 
<form action= "fileupload.action" method= "post" enctype= "Multipart/form-data" >
    Username: <input type= "text" name= "username" ><br>
    file: <input type= "file" name= "file" ><br>
    
    <input type= "Submit" value= "Submit" >
  </form>  

The next step is to fileuploadaction part of the code, because the STRUTS2 provides a good internship for both uploads and downloads, so in the action section we just need to write very little code:

public class Fileuploadaction extends Actionsupport {private String username;
  
  Note that file does not refer to the file itself uploaded by the front-end JSP, but rather the file uploaded to the files stored in the temporary folder under the private filename;
  
  The name of the file being submitted is private String filefilename;

  The MIME type of file submitted over is private String filecontenttype;
  Public String GetUserName () {return username;
  } public void Setusername (String username) {this.username = username;
  Public file GetFile () {return file;
  public void Setfile (file file) {this.file = file;
  Public String Getfilefilename () {return filefilename;
  } public void Setfilefilename (String filefilename) {this.filefilename = Filefilename;
  Public String Getfilecontenttype () {return filecontenttype;
  } public void Setfilecontenttype (String filecontenttype) {this.filecontenttype = Filecontenttype; @Override public String Execute () throws Exception {string root = Servletactioncontext.getservletcontext () . getreAlpath ("/upload");
    
    InputStream is = new FileInputStream (file);
    
    OutputStream OS = new FileOutputStream (new File (Root, Filefilename));

    System.out.println ("Filefilename:" + filefilename);
    Since file is a file stored in a temporary folder, we can print its filename and file path to see if the filefilename is the same as before System.out.println ("file:" + file.getname ());
    
    System.out.println ("File:" + File.getpath ());
    byte[] buffer = new BYTE[500];
    
    int length = 0;
    while ( -1!= (length = is.read (buffer, 0, buffer.length)) {os.write (buffer);
    } os.close ();
    
    Is.close ();
  return SUCCESS;

 }
}

First of all, we have to be clear that the file here is not really refer to the JSP uploaded files, when the file upload, Struts2 will first look for Struts.multipart.saveDir (this is in default.properties inside). The location specified by this name, we can create a new Struts.properties property file to specify the location of this temporary file, if not specified, then the file will be stored in Tomcat's Apache-tomcat-7.0.29\work\ Catalina\localhost\ directory, and then we can specify the file upload location, through the output stream to write it into the flow inside the line, then we can see in the folder we uploaded files.

File upload we also need to download it down, in fact, struts2 file download principle is very simple, is to define an input stream, and then write the file into the input stream inside the line, the key configuration or in the Struts.xml configuration file configuration:

The Filedownloadaction code is as follows:

public class Filedownloadaction extends Actionsupport
{public
  inputstream getdownloadfile ()
  {
    Return Servletactioncontext.getservletcontext (). getResourceAsStream ("upload/Address Book September 4, 2012. xls");
  }
  
  @Override public
  String execute () throws Exception
  {return
    SUCCESS;
  }
}

Let's see, this action just defines an input stream and then gives it the getter method, and then we look at the Struts.xml configuration file:

    <action name= "FileDownload" class= "com.xiaoluo.struts2.FileDownloadAction" >
      <result name= "Success" Type= "Stream" >
        <param name= "contentdisposition" >attachment;filename= "Address Book September 4, 2012. xls" </param >
        <param name= "InputName" >downloadFile</param>
      </result>
    </action>

Struts.xml configuration file There are several places we should note that first is the type of result, where we previously defined a action,result where we basically do not write the type attribute, because the default is the way the request is forwarded (dispatcher). In addition to this property generally there are redirect (redirect) and so on these values, because we are using file download, so type must be defined as the stream type, tell action this is the file download Result,result elements in general there are param child elements, This is used to set the file download parameters, InputName This property is to get the action of the file input stream, name must and action in the input stream attribute name, and then the Contentdisposition property, This property is generally used to specify what we want to do with the downloaded file, if the value is attachment, will pop up a download box, let the user choose whether to download, if not set this value, then the browser will first see if they can open the downloaded file, if you can, will open the downloaded file directly, (this is certainly not what we need), another value is filename, which is the file download name prompted by the file. After configuring this information, we will be able to implement the download function of the file.

struts2 multiple file upload :

In fact, multiple file upload and single file upload principle, single file upload past is a single files, multiple files uploaded past is a list<file> set or a file[] array, first we look at the front-end JSP part of the code, Here I use jquery to implement the dynamic Add File download box and the dynamic delete download box:

  <script type= "Text/javascript" src= "script/jquery-1.8.1.js" ></script> <script type= "Text/javascript" "> $ (Function () {$ (" #button "). Click (function () {var html = $ (" <input type= ' file
        ' name= ' file ' > ');
        
        var button = $ ("<input type= ' button ' name= ' button ' value= ' delete ' ><br>");
        
        $ ("#body div"). Append (HTML). append (button);
          Button.Click (function () {html.remove ();
        Button.remove (); })}) </script>  

The

File name must all be named file, and then the action code that handles multiple file uploads is as follows:

public class FileUploadAction2 extends Actionsupport {private String username;
  
  Here use List to store uploaded files, file also refers to temporary files in the temporary folder, rather than the real uploaded files private list<file> file;
  
  This List holds the name of the file, and the file in list<file> should be private list<string> filefilename;

  Private list<string> Filecontenttype;
  Public String GetUserName () {return username;
  } public void Setusername (String username) {this.username = username;
  Public list<file> GetFile () {return File;
  public void Setfile (list<file> file) {this.file = file;
  Public list<string> Getfilefilename () {return filefilename;
  public void Setfilefilename (list<string> filefilename) {this.filefilename = Filefilename;
  Public list<string> Getfilecontenttype () {return filecontenttype;
  public void Setfilecontenttype (list<string> filecontenttype) {this.filecontenttype = Filecontenttype; } @OVerride public String Execute () throws Exception {string root = Servletactioncontext.getservletcontext (). Getrealp
    
    Ath ("/upload");
      
      for (int i = 0; i < file.size (); i++) {InputStream is = new FileInputStream (File.get (i));
      
      OutputStream OS = new FileOutputStream (new File (Root, Filefilename.get (i)));
      
      byte[] buffer = new BYTE[500];
      
      @SuppressWarnings ("unused") int length = 0;
      while ( -1!= (length = is.read (buffer, 0, buffer.length)) {os.write (buffer);
      } os.close ();
    Is.close ();
  return SUCCESS;

 }
}

It also writes it into an output stream so that we can see multiple files uploaded in the folder.

The next file download is the same as the file download just now, Struts.xml is the same, here will not repeat the

Summary: in general, STRUTS2 provided by the file upload download mechanism simplifies our many code, we can use the mechanism in future projects, we can also use the FileUpload component to upload files, this is because of personal preferences decision!

About Javaweb in the file upload and download function of the content is so much, 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.