首先导入依赖、配置web文件以及struts2的配置
web文件:
依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 引入struts的核心 -->
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.35</version>
</dependency>
struts2的配置:
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="uploadAction_*" class="com.sw.action.UploadAction" method="{1}">
<result>index.jsp</result>
</action>
</package>
然后写Java文件:
package com.sw.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private File picture;//页面上的文件选择框的name
private String pictureFileName;//xxxFileName xxx代表页面上的文件选择框的name
HttpServletRequest request;
//单文件上传的action
public String upload() {
//将上传的文件保存
try {
//BufferedInputStream bis=new BufferedInputStream(new FileInputStream(picture));
//将文件保存到服务器中
//获取当前项目所在服务器的路径
request=ServletActionContext.getRequest();
//获取项目的真实路径
String path=request.getRealPath("/images");
String extName=pictureFileName.substring(pictureFileName.lastIndexOf('.'));
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String fileName=sdf.format(new Date());
//通过保存文件的路径和文件名称创建文件对象
File f=new File(path+"/"+fileName+extName);
//使用文件帮助类的复制文件的方法
FileUtils.copyFile(picture, f);
//通过保存文件的路径和文件名称创建文件对象
/*File f=new File(path+"/"+pictureFileName);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f));
//创建一个保存读取出来的数据的字节数组
byte[] b=new byte[1024];
//每次读取1kb
int len=bis.read(b);
while(len!=-1) {//说明文件流中的数据没有读完
bos.write(b, 0, len);//将上一次读取的1kb数据写出
len=bis.read(b);//继续读取1kb数据
}
bos.close();
bis.close();*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
public String getPictureFileName() {
return pictureFileName;
}
public void setPictureFileName(String pictureFileName) {
this.pictureFileName = pictureFileName;
}
public File getPicture() {
return picture;
}
public void setPicture(File picture) {
this.picture = picture;
}
}
最后在jsp中调用方法
<form action="uploadAction_upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="picture">
<input type="submit" value="上传">
</form>