File upload (multi-file upload)/download

Source: Internet
Author: User

Usually we will be involved in uploading files and downloading files, before the STRUTS2 framework, we are using Apache under the Commons sub-project FileUpload components to upload files, but in that case, the code looks cumbersome, and not flexible, After learning Struts2, struts2 for file upload download provides a better implementation mechanism, here I separately on the file download and multi-file upload source code to do a bit of talk

File Upload

First create a JSP page (for multiple file uploads)

<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" + request.getservername () + ":" +Request.getserverport ()+ path + "/";%><%@ taglib uri= "/struts-tags" prefix= "s"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Success.jsp page (used to display the file and file type after the upload was successful)

Import= "java.util.*" pageencoding= "UTF-8"%><%    = request.getcontextpath ();     = Request.getscheme () + "://"            + request.getservername () + ":" + Request.getserverport (            )+ path + "/"  ; %><%@ taglib uri= "/struts-tags" prefix= "s"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >    file you uploaded is:<s:property value= "Uploadfilename"/><br/>     file type:<s:property value= "Uploadcontenttype"/></body >

Next create the Uploadaction class

 Packagecn.happy.action;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportOrg.apache.struts2.ServletActionContext;ImportCom.opensymphony.xwork2.ActionContext;ImportCom.opensymphony.xwork2.ActionSupport; Public classUploadactionextendsActionsupport {//properties for uploading files    Privatefile[] upload; //types of uploaded files    Privatestring[] Uploadcontenttype; //name of the uploaded file    Privatestring[] Uploadfilename; //the address of the uploaded file    PrivateString Savepath; @Override PublicString Execute ()throwsException {byte[] buffer=New byte[1024];  for(inti = 0; i < upload.length; i++) {                        //create an input stream to upload filesFileInputStream fis=NewFileInputStream (Getupload () [i]); //build the output stream of the uploaded file, getimagefilename () [i]FileOutputStream fos=NewFileOutputStream (Getsavepath () + "\ \" +getuploadfilename () [i]); intLength=fis.read (buffer);  while(length>0) {fos.write (buffer,0, length); Length=fis.read (buffer);            } fis.close ();            Fos.flush ();        Fos.close (); }        returnSUCCESS; }                 PublicString Getsavepath () {returnServletactioncontext.getservletcontext (). Getrealpath (Savepath); }     Public voidSetsavepath (String savepath) { This. Savepath =Savepath; }         Publicfile[] Getupload () {returnupload; }     Public voidsetupload (file[] upload) { This. Upload =upload; }     Publicstring[] Getuploadcontenttype () {returnUploadcontenttype; }     Public voidSetuploadcontenttype (string[] uploadcontenttype) { This. Uploadcontenttype =Uploadcontenttype; }     Publicstring[] Getuploadfilename () {returnUploadfilename; }     Public voidsetuploadfilename (string[] uploadfilename) { This. Uploadfilename =Uploadfilename; }                    }

Finally write the configuration file Struts.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts    Public " -//apache software foundation//dtd Struts Configuration 2.3//en "    http://struts.apache.org/dtds/struts-2.3.dtd" ><struts>    <!--dynamic method call--     <constant name= "Struts.devmode" value= "false"/>            <  Package extends= "Struts-default" >                class= "Cn.happy.action.UploadAction" method= "execute" >            <param name= "Savepath" >/image</param>           <result name= "Success" >/upload/success.jsp </result>        </action>    </Package ></struts>

Achieve effect display

After selecting a file

File download

Writing JSP pages

Import= "java.util.*" pageencoding= "Utf-8"%><%== request.getscheme () + "://" + Request.getservername () + ":" +request.getserverport () +path+ "/"; %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Creating the Filedownaction Class

 PackageAction;ImportJava.io.BufferedInputStream;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.InputStream;ImportOrg.apache.struts2.ServletActionContext;ImportCom.opensymphony.xwork2.ActionSupport; Public classFiledownactionextendsActionsupport {//read the directory of downloaded files    PrivateString InputPath; //Download the file name    PrivateString FileName; //read the input stream of the downloaded file    PrivateInputStream InputStream; //types of download files    PrivateString Conetnttype; //Create InputStream input stream     PublicInputStream getInputStream ()throwsIOException {System.out.println ("123"); String Path=Servletactioncontext.getservletcontext (). Getrealpath (InputPath); return NewBufferedinputstream (NewFileInputStream (path+ "\ \" +FileName)); } @Override PublicString Execute ()throwsexception{returnSUCCESS; }             PublicString Getinputpath () {returnInputPath; }     PublicString GetFileName () {returnFileName; }     PublicString Getconetnttype () {returnConetnttype; }     Public voidSetinputpath (String inputpath) { This. InputPath =InputPath; }     Public voidsetfilename (String fileName) {filename=FileName; }     Public voidSetinputstream (InputStream inputstream) { This. InputStream =InputStream; }     Public voidSetconetnttype (String conetnttype) { This. Conetnttype =Conetnttype; }}

Writing a configuration file Struts.xml

<?xml version= "1.0" encoding= "UTF-8"? ><!DOCTYPE Struts public"-//apache software foundation//dtd Struts Configuration 2.3//en" "Http://struts.apache.org/dtds/struts-2.3.dtd" > <struts> <constant name= "Struts.devmode" value= "true" ></constant> < PackageName= "Default" namespace= "/"extends= "Struts-default" > <action name= "Download"class= "action. Filedownaction "> <param name=" InputPath ">/image</param> <result name=" succ                ESS "type=" stream "> <param name=" ContentType ">application/octet-stream</param> <param name= "InputName" >inputStream</param> <param name= "Contentdisposition" >attachment ; Filename= "${filename}" </param> <param name= "buffersize" >4096</param> </ Result> </action> </ Package> </struts>

Finally, create an image file in the Webroot directory to save the downloaded files

Achieve results

Click File Download

Additional

Importing JAR Packages

Web. XML configuration

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><display-name></display-name> <filter> <filter-name>struts2</filter-name> < filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</we Lcome-file> </welcome-file-list></web-app>

File upload (multi-file upload)/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.