public class TypeAction extends BaseAction<Type> {
//图 片上传
protected FileImage fileImage;

public String add() throws Exception {

//有上传图片的时候才设置
if (fileImage != null) {
String pic=fileUpload.uploadFile(fileImage);
model.setImage(pic);
}
typeService.save(model);
return "addOK";
}
}public class FileImage { private File file; private String contentType; private String filename; public File getFile() {
return file;
} public String getContentType() {
return contentType;
} public String getFilename() {
return filename;
} public void setUpload(File file) {
this.file = file;
} public void setUploadContentType(String contentType) {
this.contentType = contentType;
} public void setUploadFileName(String filename) {
this.filename = filename;
}}public class FileUploadUtil implements FileUpload { private String filePath;
{
String resource = this.getClass().getResource("/").getPath();
filePath = new File(resource).getParentFile().getParentFile().getPath() + "\\image";
}
// 1: 通过文件名获取扩展名
private String getFileExt(String fileName){
return FilenameUtils.getExtension(fileName);
}

// 2: 生成UUID随机数,做为新的文件名
private String newFileName(String fileName){
String ext=getFileExt(fileName);
return UUID.randomUUID().toString() + "." + ext;
}

public String uploadFile(FileImage fileImage){
// 获取新唯一文件名
String pic=newFileName(fileImage.getFilename());
try {
FileUtil.copyFile(fileImage.getFile(),new File(filePath,pic));
return pic;
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
fileImage.getFile().delete();
}
} public void delete(String fileName) {
FileUtil.deleteContents(new File(filePath,fileName));
}

}