1.在action中定义三个属性及set方法
/**
* 文件上传提供 的三个属性
* 三个属性的前缀名"upload"要与页面中上传项的name一致
*/
private String uploadFileName;//文件名称
private File upload; //上传文件
private String uploadContentType;//文件类型
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
2.编写 Action
/**
* 保存客户的方法:save
* @throws IOException
*/
public String save() throws IOException {
//文件上传
if(upload != null){
//设置文件上传路径
String path= "d:/upload";
//设置随机文件名
String uuidFileName = UploadUtils.getUUIDName(uploadFileName);
//设置目录分离
String realPath = UploadUtils.getPath(uuidFileName);
//设置文件路径
String url = path+realPath;
File file = new File(url);
if(!file.exists()){
file.mkdirs();
}
//文件上传
File destFile = new File(url+"/"+uuidFileName);
FileUtils.copyFile(upload, destFile);
customer.setCust_image(url+"/"+uuidFileName);
}
customerService.save(customer);
return "saveSuccess";
}
3.配置文件上传拦截器
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">2097152</param>
<param name="fileUpload.allowedExtensions">.jpg,png</param>
</interceptor-ref>