Java struts2 Implementation of File upload download function _java

Source: Internet
Author: User
Tags create index

First talk about STRUTS2 implementation of the file upload and download the principle of implementation of the example:

Struts 2 is uploaded via Commons fileupload file.

Commons fileupload by saving the HTTP data to a temporary folder, then struts uses the FileUpload interceptor to bind the file to an instance of the action. So we can upload files in the local file mode of Operation browser.

Specific Implementation :

First, create index.jsp page

<body>
 <s:form action= "upload" method= "post" theme= "simple" enctype= "Multipart/form-data" >
<table align= "center" width= "50%" border= "1" >
<tr>
  <td> Select Upload file </td>
  <td id= " More ">
   <s:file name=" "File" ></s:file>
   <input type= "button" value= "Add more ..." onclick= " Addmore () ">
  </td>
 </tr>
<tr>
  <td><s:submit type=" button "value=" Submit "onclick=" return Checkf () "/></td>
  <td><s:reset value=" Reset "></s:reset> </td>
 </tr>
</table>
<table align= "center" width= "50%" border= "1" >
<tr>
<td> Testing .txt</td>
<td>
  <a href= "<s:url value= ' download.action ' ><s:param name= ' fileName ' > Test .txt</s:param> </s:url> ' > Download </a>
</td>
</tr>
</table>
</s:form>
</body>

Create a result.jsp page

<body>
<s:form>
 <div style= "border:1px solid black" > successfully uploaded files:<br> <ul
  style= "List-style-type:decimal" >
 <s:iterator value= "#request. FileName" id= "file" status= "status" >
   < li><s:property/> </li>
 </s:iterator>
  </ul>
 </div>
</s:form >
</body>

Of course, don't forget to add the struts2 tag on each page <% @taglib prefix= "s" uri= "/struts-tags"%>

Second, create Updown.js file, reference in index.jsp

function Checkf () {
 var files = document.getelementsbyname ("file");
 if (files[0].value.length!=0) {return
   true;
  } else{
  Alert ("Please select File");
  return false;
  }
}
function Addmore ()
{
 var td = document.getElementById ("more");
 var br = document.createelement ("br");
 var input = document.createelement ("input");
 var button = document.createelement ("input");
 Input.type = "File";
 Input.name = "File";
 Button.type = "button";
 Button.value = "Remove";
  Button.onclick = function ()
 {
  td.removechild (BR);
  Td.removechild (input);
  Td.removechild (button);
  Td.appendchild (BR);
 Td.appendchild (input);
 Td.appendchild (button);

Third, create Updownloadaction.java

Package com.action;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.io.UnsupportedEncodingException;
Import java.util.List;
Import Javax.servlet.http.HttpServletRequest;
Import Com.opensymphony.xwork2.ActionSupport;

Import Org.apache.struts2.ServletActionContext;
 public class Updownloadaction extends Actionsupport {private static final long serialversionuid = 1L; Private list<file> file;//corresponding JSP File label private list<string> filefilename;//Private list<string> fil econtenttype;//private string filename;//Get pram parameter @SuppressWarnings in JSP ("deprecation")//File upload public string UPLOADF Iile () throws Exception {String root = Servletactioncontext.getservletcontext (). Getrealpath ("/upload");//upload path S
  Ystem.out.println (root);
  InputStream InputStream;
  File DestFile;
  OutputStream OS; for (int i = 0; i < filE.size ();
   i++) {InputStream = new FileInputStream (File.get (i));
   DestFile = new File (root, This.getfilefilename (). get (i));
   OS = new FileOutputStream (destfile);
   byte[] buffer = new byte[400];
   int length = 0;
   while (length = inputstream.read (buffer) > 0) {os.write (buffer, 0, length);
   } inputstream.close ();
  Os.close ();
  HttpServletRequest request = Servletactioncontext.getrequest ();
  Request.setattribute ("FileName", filefilename);
 return SUCCESS; //File Download public InputStream Getdownloadfile () throws FileNotFoundException, unsupportedencodingexception {System

  . Out.println (GetFileName ());
      If the download file name is Chinese, the character encoding Conversion servletactioncontext.getresponse (). SetHeader ("Content-disposition", "Attachment;filename="
  + Java.net.URLEncoder.encode (fileName, "UTF-8"));
  InputStream InputStream = new FileInputStream ("f:/"//using absolute path, download "test. txt" file + this.getfilename () from the path);
  System.out.println (InputStream);
 return inputstream; }//Download publIC String DownloadFile () throws Exception {return SUCCESS;
 Public String GetFileName () throws unsupportedencodingexception {return fileName; public void Setfilename (String fileName) throws unsupportedencodingexception {this.filename = new String (Filenam
 E.getbytes ("Iso8859-1"), "Utf-8");

 }
 }

Note: The property's get and set methods have been omitted.

Four, finally is the configuration file

1, web.xml Configuration

<filter> 
  <filter-name>struts2</filter-name> 
  <filter-class> org.apache.struts2.dispatcher.filterdispatcher</filter-class> 
 </filter> 
  
 <filter-mapping > 
  <filter-name>struts2</filter-name> 
  <url-pattern>/*</url-pattern> 
 </filter-mapping>

2, Struts.xml Configuration

<struts> <constant name= "struts.i18n.encoding" value= "Utf-8" ></constant> <constant name= "
  Struts.multipart.saveDir "value=" f:\ "></constant> <package name=" struts2 "extends=" Struts-default "> <action name= "Upload" class= "com.action.UpDownloadAction" method= "Uploadfiile" > <result name= "Success" > /jsp/result.jsp</result> <interceptor-ref name= "FileUpload" > <!--maximumsize (optional)-
 The maximum length (in bytes) that this interceptor allows to upload to the action file. Note that this parameter is not related to the attribute defined in Webwork.properties, the default 2mb--> <param name= "MaximumSize" >409600</param> <!-- Allowedtypes (optional)-a comma-separated list of contenttype types, such as text/html, that are allowed by this interceptor to pass to the action contenttype. If not specified, allow any upload type. > <param name= "allowedtypes" > Text/plain </param> </interceptor-ref> <intercept Or-ref name= "Defaultstack" ></interceptor-ref> </action> <action name= "Download" Com.action.UpDownloadAction "method=" DownloadFile "; <result name= "Success" type= "Stream" > <!--Specify file download type application/octet-stream default value can download all types--> <param n
    Ame= "ContentType" > Application/txt; </param> <!--Specify the file name and display of the download, but pay attention to the problem of garbled Chinese name, the solution is: encoding processing--> <!--contentdisposition is the processing of file downloads, including inline ( inline) and attachments (attachment), which are inline by default, are configured when using attachments: attachment;filename= "filename." --> <param name= "contentdisposition" > Attachment;filename= "${filename}" </param> <!--by GE The Tdownloadfile () method obtains the inputstream--> <param name= "InputName" >downloadFile</param> <!--Specify the cache size of the download file- -> <param name= "buffersize" >2048</param> </result> </action> </package> </st
 Ruts>

A simple Struts2 multiple file upload and single file download is achieved.

The above is the entire content of this article, I hope to help you learn.

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.