这里只走一个简单但透彻的流程,细节以后可能会补充,但还是自己去度娘找struts2的文件原理吧,要是这点自学能力都没有还当什么程序猿
~~
╮(╯▽╰)╭
前台jsp文件
form表单那个enctype="multipart/form-data"我想我不用提醒了吧
Action类
属性要点,我想我注释已经解释得很透彻了
方法体要点,我想我注释已经解释得很透彻了
各个String的存储数据在控制台上的展示
目录下文件效果图
然后。。。就完了,就是那么简单
上面套路流程基本可以照搬,但要自己理解透彻才行
代码展示(不然怎么复制粘贴,只贴上面那几行哈,jsp跟Action里面无关代码太多,看了也没用,话说看那么多干嘛,要不然表情包也送给你算了)
jsp
<input class="form190px" id="file" name="file" type="file" />
UserAction
package cn.com.do1.component.usertest.ui;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class UserAction extends BaseAction {
@Resource
private IUserService myUserService;
private String dqdp_csrf_token;
private UserPO userPO;
private String[] ids;
private String personId;
private int page;
private File file; //要与前面的input 的name属性相同,File为基础的 java.io.File 就行
private String fileFileName; //name的属性名+固定字段FileName
private String fileContentType; //name的属性名+固定字段ContentType
/*get/set方法省略不截*/
public void uploadFile(){
try {
String pathString= ServletActionContext.getRequest().getRealPath("pic")+"\\";//获取项目工程的绝对路径
String fileType=fileFileName.substring(fileFileName.lastIndexOf("."));//获取文件类型
String fileName=UUID.randomUUID().toString();//UUID.randomUUID为随机生成36位识别码,防止文件名重复
String newAbsolutePath=pathString+fileName+fileType;//新文件的绝对路径
File newFile=new File(newAbsolutePath);//构造新的文件
FileUtils.copyFile(file, newFile);//复制到新的文件,至此完成
//无关代码
addJsonObj("headPortrait", fileName+fileType);
setActionResult("0","添加成功");
System.out.println("fileFileName:"+fileFileName);
System.out.println(("fileContentType:"+fileContentType));
System.out.println("fileName:"+fileName);
System.out.println("newAbsolutePath:"+newAbsolutePath);
} catch (IOException e) {
e.printStackTrace();
}
doJsonOut();
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}