`

Struts 2 File Uploads

阅读更多
Create view files:

Let us start with creating our view which will be required to browse and upload a selected file. So let us create a index.jsp with plain HTML upload form that allows the user to upload a file:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload your file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload"/>
   </form>
</body>
</html>

There are couple of points worth noting in the above example. First of all, the form's enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form's action method upload and the name of the file upload field - which is myFile. We need this information to create the action method and the struts configuration.

Next let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success.


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>

Following will be the result file error.jsp in case there is some error in uploading the file:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Error</title>
</head>
<body>
There has been an error in uploading the file.
</body>
</html>

Create action class:

Next let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location:

package com.tutorialspoint.struts2;

import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException; 

import com.opensymphony.xwork2.ActionSupport;

public class uploadFile extends ActionSupport{
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute()
   {
      /* Copy file to a safe location */
      destPath = "C:/apache-tomcat-6.0.33/work/";

      try{
     	 System.out.println("Src File name: " + myFile);
     	 System.out.println("Dst File name: " + myFileFileName);
     	    	 
     	 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;
   }
}

The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Intercetpor does all the heavy lifting for us. The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern:

[your file name parameter] - This is the actual file that the user has uploaded. In this example it will be "myFile"

[your file name parameter]ContentType - This is the content type of the file that was uploaded. In this example it will be "myFileContentType"

[your file name parameter]FileName - This is the name of the file that was uploaded. In this example it will be "myFileFileName"

The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automaically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns "success" if everything goes fine otherwise it returns "error".

Configuration files:

Following are the Struts2 configuration properties that control file uploading process:

SN	Properties & Description
1	struts.multipart.maxSize
The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M.
2	struts.multipart.parser
The library used to upload the multipart form. By default is jakarta
3	struts.multipart.saveDir
The location to store the temporary file. By default is javax.servlet.context.tempdir.
In order to change any of theses settings you can use constant tag in your applications struts.xml file, as I did to change the maximum size of a file to be uploaded. Let us have our struts.xml as follows:

<?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.multipart.maxSize" value="1000000" />

   <package name="helloworld" extends="struts-default">
   <action name="upload" class="com.tutorialspoint.struts2.uploadFile">
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>
   </package>
</struts>
Because FileUpload interceptor is a part of the defaultStack of interceptors, we do not need to configure it explicity. But you can add <interceptor-ref> tag inside <action>. The fileUpload interceptor takes two parameters (a) maximumSize and (b) allowedTypes. The maximumSize parameter sets the maximum file size allowed (the default is approximately 2MB).The allowedTypes parameter is a comma-separated list of accepted content (MIME) types as shown below:

   <action name="upload" class="com.tutorialspoint.struts2.uploadFile">
       <interceptor-ref name="basicStack">
       <interceptor-ref name="fileUpload">
           <param name="allowedTypes">image/jpeg,image/gif</param>
       </interceptor-ref>
       <result name="success">/success.jsp</result>
       <result name="error">/error.jsp</result>
   </action>

Following is the content of web.xml file:
<?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"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <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>
</web-app>

Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/upload.jsp. This will give you following screen:


Now select a file "Contacts.txt" using Browse button and click upload button which will upload the file on your serve and you should see the net page. You can check the uploaded file should be saved in C:\apache-tomcat-6.0.33\work.


Note that the FileUpload Interceptor deletes the uploaded file automatically so you would have to save uploaded file programatically at some location before it gets deleted.

Error Messages:

The fileUplaod interceptor uses several default error message keys:
SN	Error Message Key & Description
1	struts.messages.error.uploading
A general error that occurs when the file could not be uploaded.
2	struts.messages.error.file.too.large
Occurs when the uploaded file is too large as specified by maximumSize.
3	struts.messages.error.content.type.not.allowed
Occurs when the uploaded file does not match the expected content types specified.
You can override the text of these messages in WebContent/WEB-INF/classes/messages.properties resource files.
分享到:
评论

相关推荐

    struts2图片上传并预览

    确保`struts2-core`和`struts2-convention-plugin`以及`struts2-file-uploading-plugin`在你的类路径中。 2. 配置struts.xml:在`struts.xml`配置文件中,启用文件上传,设置`struts.multipart.saveDir`属性指定...

    struts2文件上传的两种方法

    Struts2作为一款流行的Java Web框架,提供了丰富的功能来处理用户表单数据,其中包括文件上传。文件上传在现代Web应用中十分常见,如用户头像、文档分享等场景。Struts2提供了两种主要的文件上传方式:单文件上传和...

    Struts2文件上传源码

    File destinationFile = new File("uploads/" + fileFileName); Files.copy(file, destinationFile, StandardCopyOption.REPLACE_EXISTING); return "success"; } catch (IOException e) { addFieldError("file...

    Struts2实现文件上传

    通常,你需要引入`struts2-convention-plugin`和`struts2-file-uploading-plugin`。 2. **表单设置**: 在HTML或JSP页面中,创建一个包含`enctype="multipart/form-data"`属性的表单,这指示浏览器以多部分格式...

    Struts2实现文件上传功能

    Struts2是一个基于MVC(Model-View-Controller)设计模式的Java web框架,它极大地简化了Java web应用的开发工作。在Struts2中,文件上传是一个常见的需求,尤其在用户需要提交表单并附带文件时。下面将详细阐述如何...

    struts2+jxl图片上传,io流

    File saveDir = new File("uploads"); if (!saveDir.exists()) { saveDir.mkdir(); } File savedFile = new File(saveDir, imageFileName); FileUtils.copyInputStreamToFile(imageFile.getInputStream(), ...

    Struts2实现文件的上传下载

    然后,在Struts2的Action类中,可以创建一个`File`或`java.io.File`类型的属性,用于接收上传的文件。同时,还需要一个对应的`String`类型属性来保存文件名。例如: ```java private File file; private String ...

    struts2s上传文件

    File saveFile = new File("uploads/" + uploadFileFileName); file.write(saveFile); // 处理其他逻辑... } catch (Exception e) { // 处理异常... } return "success"; } ``` 5. **安全考虑**:文件上传时...

    Struts2多文件上传下载实例

    Struts2是一个强大的MVC(模型-视图-控制器)框架,广泛应用于Java Web开发中。在实际项目中,文件上传和下载功能是必不可少的,本实例将详细讲解如何在Struts2框架下实现单个文件及多个文件的上传与下载。 首先,...

    在Struts 2中实现文件上传

    此外,使用 `&lt;s:file&gt;` 标签将文件上传控件与 Action 中的某个字段(如 `myFile`)绑定,这样 Struts 2 就知道如何处理文件上传请求。 下面是一个简单的 `FileUpload.jsp` 示例: ```jsp ; charset=utf-8" ...

    Struts2实现多文件上传

    Struts2是一个流行的Java web框架,它为开发者提供了一种结构化的MVC(Model-View-Controller)设计模式实现方式,使得开发企业级应用程序变得更加高效和便捷。在Struts2中,实现多文件上传功能是常见的需求,尤其在...

    struts2 文件上传 测试通过版

    当用户提交表单时,Struts2框架会将文件内容传递到Action类的`File`属性。在Action的execute方法中,可以使用Apache Commons FileUpload库来处理上传的文件。首先,确保在项目中引入了该库。然后,可以解析请求并...

    struts2 实现文件、图片 上传

    你需要使用Struts2提供的`File`和`FileName`注解来处理上传的文件。例如: ```java public class UploadAction extends ActionSupport { private File file; private String fileName; @FileUpload public ...

    Struts2文件批量上传.zip

    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("uploads/" + file.getOriginalFilename()))); stream.write(bytes); stream.close(); // 提示保存成功 } catch ...

    struts2上传图片

    在Struts2中,我们可以使用`struts2-convention-plugin`或者`struts2-core`提供的`&lt;s:file&gt;`标签来创建一个用于上传文件的表单元素。例如: ```html &lt;s:file name="image" label="选择图片"/&gt; 上传"/&gt; ``` ...

    Struts2批量上传文件

    File saveDir = new File("uploads"); if (!saveDir.exists()) { saveDir.mkdirs(); } FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(new File(saveDir, ...

    Struts2文件上传

    File targetFile = new File("uploads/" + fileFileName); FileUtils.copyFile(file, targetFile); // 可以在此处进行其他业务逻辑处理,如数据库存储等 // ... return SUCCESS; } catch (Exception e) { ...

    Struts2多文件上传下载源码

    &lt;constant name="struts.multipart.saveDir" value="/tmp/struts2-uploads/"/&gt; &lt;param name="maximumSize"&gt;4100000 &lt;param name="allowedTypes"&gt;image/jpeg,image/gif,application/pdf ...

    实现struts2的文件上传文件功能

    Struts2是一个非常流行的Java Web框架,用于构建可维护、可扩展且易于开发的企业级应用程序。在Struts2中,实现文件上传功能是一项常见的需求,它允许用户通过Web界面上传文件到服务器。以下是对该主题的详细解释: ...

    文件上传Struts2

    Struts2是一个强大的Java web框架,它为开发者提供了一种优雅的方式来实现MVC(Model-View-Controller)架构。在Struts2中,文件上传功能是相当常见的需求,尤其是在处理用户提交表单时,比如上传图片、文档等。本文...

Global site tag (gtag.js) - Google Analytics