Struts2 file upload problem in Java

  • 2020-04-01 03:58:55
  • OfStack

The first part of the page is upload_file.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>Upload File</title>
</head>
<body>
  <form action="UploadFile" method="post" enctype="multipart/form-data">
    <!-- File domain -->
    <input type="file" name="source" /> <input type="submit" value=" upload ">
  </form>
</body>
</html>

For the form to upload the file, metho must be set to post and enctype must be set to multipart/form-data.

From the above code, you can see that the form is submitted to UploadFile for processing, so we'll configure it in struts.xml as follows:


<action name="UploadFile" class="com.lidi.action.UploadAction">
  <result name="success">/uploadResult.jsp</result>
  <!--fileUpload Interceptor, which can be used to limit the type and size of uploaded documents  -->
  <interceptor-ref name="fileUpload">
  <!--  Limit file size 20M , in bytes  -->
    <param name="maximumSize">20971520</param>
  </interceptor-ref>
  <!-- The default interceptor must be declared in fileUpload Behind the interceptor  -->
  <interceptor-ref name="defaultStack" />
 </action>

FileUpload interceptor for setting upload paths and limiting file types and sizes.

About limiting file size, light has < Param name = "maximumSize >" No, it has to be in < Struts> Under the tag add


<constant name="struts.multipart.maxSize" value="21000000"/>

This line of code says the whole project all to upload files to allow to upload the maximum file size, that is to say, this project to upload any single file size should not exceed 21000000 bytes (about 20 m), if not add this line of code in project, the default allows the upload file size up to 2 m, so it is also a breakthrough the limitation of struts 2 can upload only 2 m file.

About limiting file types, if you need to limit it to image files, then < Interceptor> You can configure it like this


<!--  The Settings only allow uploading image files  -->
<intercepter-ref name="fileUpload">
  <param name="allowedTypes">image/bmp, image/x-png, image/gif, image/jpeg</param>
</intercepter-ref>
<interceptor-ref name="defaultStack" />

< Param name = "allowedTypes >" The values in the tag are the MIME type of the file. The MIME type of the commonly used file can be found in %TOMCAT_HOME%\conf\web.xml.

If you want to limit it to a word file, you can < Interceptor> You can configure it like this


<!--  Only uploads are allowed word The document  -->
<intercepter-ref name="fileUpload">
  <param name="allowedTypes">application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
</intercepter-ref>
<interceptor-ref name="defaultStack" />

However, I feel that this is a better way to limit file types than to use javascript to implement restrictions on the front end.

UploadAction, UploadAction must have a private property named source, which is the same as the file field name in upload_file.jsp.

Private String sourceFileName; // file name of the file to be uploaded
Private String sourceContentType; // the file type of the file to be uploaded
The format of the two variable names is the same as the prefix source and upload_file.jsp with the file field name attribute.

In summary, for example, the name of the file field in upload_file.jsp = "ABC", which is the definition in the Action


private File abc;
private String abcFileName;
private String abcContentType; 

ABC automatically gets the file object to be uploaded, abcFileName automatically gets the file name, and abcContentType automatically gets the file type.

Here's what I want to highlight about the upload path.

That's fine if you're uploading to an absolute path, but how do you get the full path to the upload folder at the root of your project?

I tried it

ServletActionContext. GetServletContext (.) getRealPath ("/upload ");
But null is returned. Also used

ServletActionContext. GetRequest (). GetRealPath ("/upload ");
Still returns null. Looking it up on the web, however, many people recommend it, proving that it might work in some cases, but others, like me, recommend a new way to make UploadAction implement the ServletContextAware interface. The specific approach is as follows:


public class UploadAction extends ActionSupport implements ServletContextAware {

  
  private ServletContext context; 

  public ServletContext getContext() {
    return context;
  }

  public void setContext(ServletContext context) {
    this.context = context;
  }
  
  @Override
  public void setServletContext(ServletContext context) {
    this.context = context;
  }
}

Then use the


String path = context.getRealPath("/upload");//Important: no slashes

Gets the path to the upload folder. Then perform the upload:



File savefile = new File(path, sourceFileName);
FileUtils.copyFile(source, savefile);

I personally recommend this approach because it seems to avoid ensuring that projects get the right path when they are packaged and moved to other environments.

Paste the full code for UploadAction. Java


package com.lidi.action;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport implements ServletContextAware {
  
  private static final long serialVersionUID = 1L;
  private File source;//File to be uploaded
  private String sourceFileName;//File to be uploaded The name of the file 
  private String sourceContentType; //File to be uploaded Type of file 
  private ServletContext context; //important
  
  public ServletContext getContext() {
    return context;
  }
  public void setContext(ServletContext context) {
    this.context = context;
  }
  
  public File getSource() {
    return source;
  }
  public void setSource(File source) {
    this.source = source;
  }
  public String getSourceFileName() {
    return sourceFileName;
  }
  public void setSourceFileName(String sourceFileName) {
    this.sourceFileName = sourceFileName;
  }
  public String getSourceContentType() {
    return sourceContentType;
  }
  public void setSourceContentType(String sourceContentType) {
    this.sourceContentType = sourceContentType;
  } 
  @Override
  public void setServletContext(ServletContext context) {
    this.context = context;
  }
  public String execute() throws IOException {
    
    String path;
    path = context.getRealPath("/upload");//important : the slash cannot be missed 
    System.out.println(path);    
    
    File savefile = new File(path, sourceFileName);
    FileUtils.copyFile(source, savefile);
    System.out.println(savefile.getAbsolutePath());
    return SUCCESS;
  }
}

Upload the result page uploadresult.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML>
<html>
 <head>  
  <title>Upload Result</title>
 </head>
 <body>
 <p> The file name: <s:property value="sourceFileName" /></p>
 <p> File type: <s:property value="sourceContentType" /></p>
 <p> File: <a href="upload/<s:property value="sourceFileName" />"><s:property value="sourceFileName" /></a></p>
 </body>
</html>

The above is all the content of this article, I hope you can enjoy it.


Related articles: