首先新建一个上传的jsp,如下:
<%@ page language=
"java"
contentType=
"text/html; charset=UTF-8"
pageEncoding=
"UTF-8"
%>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<html>
<head>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=UTF-8"
>
<title>上传</title>
</head>
<body>
<form action=
"upload.action"
method=
"post"
enctype=
"multipart/form-data"
>
<label
for
=
"myFile"
>你要上传的文件</label>
<input type=
"file"
name=
"upload"
/><br>
<input type=
"submit"
value=
"上传"
/>
</form>
</body>
</html>
注意:form表单的提交方式必须是post,enctype必须是multipart/form-data。
其次是上传的action,如下:
package
test;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
org.apache.struts2.ServletActionContext;
public
class
UploadAction {
protected
File upload;
protected
String uploadContentType;
protected
String uploadFileName;
protected
String savePath;
public
String execute()
throws
IOException {
// 获取需要上传文件的文件路径
savePath = ServletActionContext.getServletContext().getRealPath(
"uploadFile"
);
File file =
new
File(savePath, uploadFileName);
if
(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 声明文件输入流,为输入流指定文件路径
FileInputStream input =
new
FileInputStream(upload);
byte
[] arry =
new
byte
[input.available()];
input.read(arry);
// 获取输出流,获取文件的文件地址及名称
FileOutputStream out =
new
FileOutputStream(file);
out.write(arry);
input.close();
out.close();
return
"success"
;
}
/**
* @return the upload
*/
public
File getUpload() {
return
upload;
}
/**
* @param upload
* the upload to set
*/
public
void
setUpload(File upload) {
this
.upload = upload;
}
/**
* @return the uploadContentType
*/
public
String getUploadContentType() {
return
uploadContentType;
}
/**
* @param uploadContentType
* the uploadContentType to set
*/
public
void
setUploadContentType(String uploadContentType) {
this
.uploadContentType = uploadContentType;
}
/**
* @return the uploadFileName
*/
public
String getUploadFileName() {
return
uploadFileName;
}
/**
* @param uploadFileName
* the uploadFileName to set
*/
public
void
setUploadFileName(String uploadFileName) {
this
.uploadFileName = uploadFileName;
}
/**
* @return the savePath
*/
public
String getSavePath() {
return
savePath;
}
/**
* @param savePath
* the savePath to set
*/
public
void
setSavePath(String savePath) {
this
.savePath = savePath;
}
}