1.首先在action中写如下代码
public String uploadFile() throws Exception {
String absolutePath = ServletActionContext.getServletContext().getRealPath(""); // 获取项目根路径
//文件路径
String path = absolutePath + "/" + this.savePath + "/";
//创建路径,如果目录不存在,则创建
File file = new File(path);
if(!file.exists()) {
file.mkdirs();
}
//文件路径+文件名
path +=this.getFileuploadFileName();
//1.构建输入流
FileInputStream fis = new FileInputStream(fileupload);
//2.构建输出流
FileOutputStream fos = new FileOutputStream(path);
//3.通过字节写入输出流
try {
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
fos.close();
}
return SUCCESS;
}
@JSON(serialize = false)
public File getFileupload() {
return fileupload;
}
public void setFileupload(File fileupload) {
this.fileupload = fileupload;
}
@JSON(serialize = false)
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getFileuploadFileName() {
return fileuploadFileName;
}
public void setFileuploadFileName(String fileuploadFileName) {
this.fileuploadFileName = fileuploadFileName;
}
public String getFileuploadContentType() {
return fileuploadContentType;
}
public void setFileuploadContentType(String fileuploadContentType) {
this.fileuploadContentType = fileuploadContentType;
}
2.在struts.xml中写入:
3.客户端jsp页面中:
*注意:form表单一定要是:method ="POST" enctype ="multipart/form-data"