1、Spring配置文件中配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="5242880"/>
</bean>
2、JSP代码:
<form method="post" class="form form-horizontal" id="form-add" enctype="multipart/form-data">
<div class="row cl">
<label class="form-label col-xs-4 col-sm-3">
图片路径:
</label>
<div class="formControls col-xs-8 col-sm-9">
<input type="file" accept='image/*' id="file" name="file">
</div>
</div>
<div class="row cl">
<div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
<input class="btn btn-primary radius" type="submit" value="提交">
</div>
</div>
</form>
3、Spring的Controller方法
@RequestMapping(value = "/saved")
public void saved(Active active, MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
BufferedImage bi = ImageIO.read(file.getInputStream());
if (bi == null) {
throw new Exception("上传的文件不能正确的图片格式!");
}
String rootPath = "";
// windows下
if ("\\".equals(File.separator)) {
rootPath = classPath.substring(1, classPath.indexOf("/WEB-INF"));
rootPath = rootPath.replace("/", "\\");
rootPath += "\\";
}
// linux下
if ("/".equals(File.separator)) {
rootPath = classPath.substring(0, classPath.indexOf("/WEB-INF"));
rootPath = rootPath.replace("\\", "/");
rootPath += "/";
}
rootPath += file.getOriginalFilename();
InputStream inputStream = multipartFile.getInputStream();
DataInputStream dis = new DataInputStream(inputStream);
File file = new File(rootPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = -1;
while ((len = dis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
}
PS:
1、active为实体类对象
2、ImageIO.read用于判断上传的文件是否为正确的图片格式
3、再附加一个JS用于验证文件是否为图片的代码
function validateImg() {
var fileName = document.getElementById("file").value;
if (fileName == '') {
layer.msg("请上传图片!", {icon: 5,time:1000});
return false;
}
var suffixIndex = fileName.lastIndexOf(".");
var suffix = fileName.substring(suffixIndex + 1).toUpperCase();
if (suffix != "BMP" && suffix != "JPG" && suffix != "JPEG"
&& suffix != "PNG" && suffix != "GIF") {
layer.msg("请上传格式为BMP、JPG、JPEG、PNG、GIF的图片!", {icon: 5,time:3000});
return false;
}
return true;
}
附加:
ImageIO.read读取图片时,如果是PS软件P过的图片,会报错:Unsupported Image Type
解决方法:使用TwelveMonkeys处理图片
TwelveMonkeys的使用比较简单,只要把相关的jar包加入到类路径,他的类我们基本不会用到,只要使用jdk ImageIO或其上层的接口就行了。jdk的ImageIO有自动发现功能,会自动查找相关的编解码类并使用,而不使用jdk默认的编解码类,所以使用这个库是完全无入侵的。
imageio-core-3.3.2.jar、imageio-jpeg-3.3.2.jar、imageio-metadata-3.3.2.jar、common-image-3.3.2.jar、common-io-3.3.2.jar、common-lang-3.3.2.jar(架包都是TwelveMonkeys下的)