一、配置文件上传解析器(CommonsMultipartResolver)
1.1 设置最大的上传量(MaxUploadSize)
1.2 设置文件的编码格式(DefaultEncoding,一般使用UTF-8)
1.3 具体代码配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="MaxUploadSize" value="10485760"/>
<property name="DefaultEncoding" value="UTF-8"/>
</bean>
二、页面代码实现
2.1 需要开启多媒体标签,就是在form标签中添加enctype属性,属性值为“multipart/form-data”
2.2 添加文件上传按钮(实际上就是添加file类型的input标签)
2.3 具体代码实现如下
<form action="http://localhost:8091/file" method="post"enctype="multipart/form-data">
文件上传:<input name="pic"type="file"/>
<input type="submit"value="提交"/>
</form>
三、控制台的实现
3.1 用MultipartFile接口来接收页面传来的文件参数
3.2 参数名(uploadFile)需要和页面上文件控件的名称(name属性)保持一致
3.3 使用PicUploadResult对象(自己封装的)来进行页面回显和提示操作结果(成功或失败)
3.4 具体代码实现
@RequestMapping("fileUpload")
@ResponseBody
public PicUploadResult fileUpload(MultipartFile uploadFile){
return fileUploadService.fileUpload(uploadFile);
}
四、业务层的实现
4.1 具体代码实现
@Service
public class FileUploadServiceImpl implements FileUploadService {
private String localPath = "D:/jt-upload/";
private String imageUrl = "http://image.jt.com/";
@Override
public PicUploadResult fileUpload(MultipartFile uploadFile) {
PicUploadResult uploadResult = new PicUploadResult();
String fileName = uploadFile.getOriginalFilename();
fileName = fileName.toLowerCase();
if(!fileName.matches("^.*\\.(jpg|png|gif)$")){
uploadResult.setError(1);
}
try {
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
if((height==0) || (width==0)){
uploadResult.setError(1);
}
String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
File fileDir = new File(localPath+dateDir);
if(!fileDir.exists()){
fileDir.mkdirs();
}
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
int randomNum = new Random().nextInt(1000);
String fileType = fileName.substring(fileName.lastIndexOf("."));
String realFileName = uuid + randomNum + fileType;
String localFilePath = localPath + dateDir + "/" + realFileName;
uploadFile.transferTo(new File(localFilePath));
String imageUrlPath = imageUrl + dateDir + "/" + realFileName;
uploadResult.setUrl(imageUrlPath);
uploadResult.setHeight(height+"");
uploadResult.setWidth(width+"");
} catch (Exception e) {
e.printStackTrace();
uploadResult.setError(1);
}
return uploadResult;
}
}