Simulate a single file upload in 2 ways, the effect is as follows
The development steps are as follows:
1. Create a new web project and import the jars required for struts2 upload files, as shown below
Directory structure
2. Create new Action
first way
Copy the code code as follows:
package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
private File image; //uploaded file
private String imageFileName; //File name
private String imageContentType; //File type
public String execute() throws Exception {
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//D:/apache-tomcat-6.0.18/webapps/struts2_upload/images
System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "File uploaded successfully");
}
return "success";
}
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
}
Second way
Copy the code code as follows:
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport {
//Encapsulate the attributes of the uploaded file domain
private File image;
//Encapsulate the attributes of the uploaded file type
private String imageContentType;
//Encapsulate the attributes of the uploaded file name
private String imageFileName;
//Accept dependency injection properties
private String savePath;
@Override
public String execute() {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
//Create file output stream
System.out.println(getSavePath());
fos = new FileOutputStream(getSavePath() + "//" + getImageFileName());
//Create a file upload stream
fis = new FileInputStream(getImage());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
System.out.println("File upload failed");
e.printStackTrace();
} finally {
close(fos, fis);
}
return SUCCESS;
}
/**
* Return to the save location of the uploaded file
*
* @return
*/
public String getSavePath() throws Exception{
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
private void close(FileOutputStream fos, FileInputStream fis) {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("FileInputStream failed to close");
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("FileOutputStream failed to close");
e.printStackTrace();
}
}
}
}
struts.xml configuration file
Copy the code code 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>
<!-- This attribute specifies the request suffix that needs to be processed by Struts2. The default value of this attribute is action, that is, all requests matching *.action are processed by Struts2.
If the user needs to specify multiple request suffixes, separate the multiple suffixes with commas (,). -->
<constant name="struts.action.extension" value="do" />
<!-- Set whether the browser caches static content. The default value is true (used in production environment). It is best to turn it off during the development stage -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- When the struts configuration file is modified, whether the system will automatically reload the file, the default value is false (used in production environment), it is best to turn it on during the development stage -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- Used in development mode, so that more detailed error messages can be printed out -->
<constant name="struts.devMode" value="true" />
<!--Default view theme-->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--Solution to garbled codes-->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- Specify the maximum number of bytes allowed for uploaded files. The default value is 2097152(2M) -->
<constant name="struts.multipart.maxSize" value="10701096"/>
<!-- Set the temporary folder for uploaded files, javax.servlet.context.tempdir is used by default -->
<constant name="struts.multipart.saveDir " value="d:/tmp" />
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload2" extends="struts-default">
<action name="upload2" method="execute">
<!-- Dynamically set the attribute value of savePath -->
<param name="savePath">/images</param>
<result name="success">/WEB-INF/page/message.jsp</result>
<result name="input">/upload/upload.jsp</result>
<interceptor-ref name="fileUpload">
<!-- File filtering -->
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<!-- File size, in bytes -->
<param name="maximumSize">1025956</param>
</interceptor-ref>
<!-- The default interceptor must be placed after fileUpload, otherwise it will be invalid -->
<interceptor-ref name="defaultStack" />
</action>
</package>
</struts>
Upload form page
Copy the code code as follows:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>File upload</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do"
enctype="multipart/form-data" method="post">
File:<input type="file" name="image">
<input type="submit" value="Upload" />
</form>
<br/>
<s:fielderror />
</body>
</html>
Show results page
Copy the code code as follows:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Upload successful</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
Upload successful!
<br/><br/>
<!-- ${pageContext.request.contextPath} tomcat deployment path,
For example: D:/apache-tomcat-6.0.18/webapps/struts2_upload/ -->
<img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
<s:debug></s:debug>
</body>
</html>