Java framework --- struts file upload and download, java framework --- struts

Source: Internet
Author: User

Java framework --- struts file upload and download, java framework --- struts
Struts2 File Upload

The Struts 2 Framework provides built-in support for processing file uploads using HTML form-based file uploads. When uploading a file, it is usually stored in a temporary directory. They should be processed by the Action class or moved to a permanent directory to ensure that data is not lost.

Note that a security policy on the server may prohibit writing to a temporary directory other than the Directory and a directory belonging to the web application.

File Upload in Struts is part of the defaultStack that can be passed through org. apache. struts2.interceptor. FileUploadInterceptor class. You can still set various parameters in struts. xml, as we can see below.

View File index. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" s "uri ="/struts-tags "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

Note the following points in the above example. First, set the form's enctype attribute to multipart/form-data. This should be set to process file upload. The next point is the form action method upload and the file upload field name-myFile. We need this information to create the operation method and struts configuration.

Next, let's create a simple jsp fileSuccess. jspThe result shows that our files are successfully uploaded.

<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" s "uri ="/struts-tags "%> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> Create action class: Process uploaded files,
Package com. oumyye. fileUpload; import java. io. file; import java. io. IOException; import org. apache. commons. io. fileUtils; import com. opensymphony. xwork2.ActionSupport; public class FileUploadAction extends ActionSupport {private File myFile; private String myFileContentType; private String myFileFileName; private String destPath;/*****/private static final long serialVersionUID = 1L; @ Override public String execute () throws Exception {// TODO Auto-generated method stub destPath = "e:/upload/"; try {System. out. println ("Src File name:" + myFile); System. out. println ("My file name" + myFileFileName); System. out. println ("My File type" + myFileContentType); File destFile = new File (destPath, myFileFileName); FileUtils. copyFile (myFile, destFile);} catch (IOException e) {e. printStackTrace (); return ERROR;} return SUCCESS;} public File getMyFile () {return myFile;} public void setMyFile (File myFile) {this. myFile = myFile;} public String getMyFileContentType () {return myFileContentType;} public void setMyFileContentType (String myFileContentType) {this. myFileContentType = myFileContentType;} public String getMyFileFileName () {return myFileFileName;} public void setMyFileFileName (String myFileFileName) {this. myFileFileName = myFileFileName;} public String getDestPath () {return destPath;} public void setDestPath (String destPath) {this. destPath = destPath;} public static long getSerialversionuid () {return serialVersionUID ;}}
Configuration file:

You can use a constant tag in the struts. xml file of the application, and change the maximum size of the file to be uploaded as I do. Let's see the following in struts. xml:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name = "struts. devMode "value =" false "/> <! -- Specify that each request arrives and reload the resource file --> <constant name = "struts. i18n. reload" value = "true"/> <! -- Specifies that the configuration file is automatically reloaded after each change --> <constant name = "struts. configuration. xml. reload" value = "true"/> <! -- Configure the topic as simple --> <constant name = "struts. ui. theme" value = "simple"/> <! -- Specifies the maximum number of bytes of files that can be uploaded. The default value is 2097152 (2 M) --> <constant name = "struts. multipart. maxSize" value = "10701096"/>
<! -- File upload --> <package name = "Upload" namespace = "/" extends = "struts-default"> <action name = "upload" class = "com. oumyye. fileUpload. fileUploadAction "> <result name =" success ">/success. jsp </result> <result name = "input">/index. jsp </result> </action>

<! -- File download --> <action name = "FileDownload" class = "com. oumyye. action. fileDownload "> <result name =" success "type =" stream "> <param name =" contentType "> text/plain </param> <param name =" contentDisposition "> attachment; fileName = "$ {fileName}" </param> <param name = "inputName"> downloadFile </param> <param name = "bufferSize"> 1024 </param> </ result> </action> </package> </struts>

The following is the content in the web. xml file, which is the same as the basic configuration of Struts2.

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <display-name>Struts2_1000_FileUpload</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>*.action</url-pattern>  </filter-mapping></web-app>
The above code completes File Upload File Download View File filedownload. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> Create action class: Process uploaded files,
Package com. oumyye. action; import java. io. InputStream; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionSupport; // download public class FileDownload extends ActionSupport {
Private String fileName; public String getFileName () {return fileName;} public void setFileName (String fileName) {this. fileName = fileName;} // returns an input stream, which is an input stream as a client, but an output stream public InputStream getDownloadFile () throws Exception {this. fileName = "hello.jpg"; // obtain the resource path return ServletActionContext. getServletContext (). getResourceAsStream ("upload/" + this. fileName) ;}@ Override public String execute () throws Exception {return SUCCESS ;}}

The configuration file is the same as above.

An error may occur during download.

Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action.

Possible cause: 1. the file path is incorrect and the file is not obtained at all. In this case, you can put the statement for InputStream in system. out. output in println (). If it is null, the path is incorrect, or the file is not found if it is accurate.

2. No get method for the attribute following "<param name =" inputName ">" in the configuration file is written in the action.

Related Article

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.