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) { //set方法可以不用和属性名一样,但是前台传进来时的参数得和set方法名相同。即前台传的参数为fileImage.upload
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
}
//文件上传工具类接口
public interface FileUpload {
//实现文件上传的功能,返回上传后新的文件名称
public abstract String uploadFile(FileImage fileImage);
}
//文件上传工具类具体实现
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
private String filePath;
@Value("#{prop.filePath}")
//@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=filePath的值
public void setFilePath(String filePath) {
System.out.println(filePath);
this.filePath = filePath;
}
//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;
}
//实现文件上传的功能,返回上传后新的文件名称
@Override
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();
}
}
}
@Controller("baseAction")
@Scope("prototype")
public class BaseAction<T> extends ActionSupport implements RequestAware,SessionAware,ApplicationAware,ModelDriven<T> {
//封装了图片信息的类
protected FileImage fileImage;
//上传文件工具类
@Resource
protected FileUpload fileUpload;
public FileImage getFileImage() {
return fileImage;
}
public void setFileImage(FileImage fileImage) {
this.fileImage = fileImage;
}
//省略其他无关代码……
}
@Controller("productAction")
@Scope("prototype")
public class ProductAction extends BaseAction<Product> {
//省略其他无关代码……
public void save() throws Exception {
//fileUpload工具类被抽取了,uploadFile方法直接接受一个fileImage对象,返回新的图片名
String pic = fileUpload.uploadFile(fileImage);
model.setPic(pic);
model.setDate(new Date());
System.out.println(model);
//商品信息入库
productService.save(model);
}
public void update() {
String pic = fileUpload.uploadFile(fileImage);
model.setPic(pic);
model.setDate(new Date());
System.out.println(model);
//更新商品
productService.update(model);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有