所需jar包: commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
jsp页面: from表单加 enctype="multipart/form-data"
上传按钮 <input type="file" name="image">
上传图片方法
package com.utils;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
public class ImageUpload {
public static String uploadFile(HttpServletRequest request,
MultipartFile image) {
// 获得物理路径
String pathRoot = request.getSession().getServletContext()
.getRealPath("");
String path = "";
if (!image.isEmpty()) {
// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件类型(可以判断如果不是图片,禁止上传)
String contentType = image.getContentType();
// 获得文件后缀名称
String imageName = contentType
.substring(contentType.indexOf("/") + 1);
path = "/res/images/user/" + uuid + "." + imageName;
try {
image.transferTo(new File(pathRoot + path));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
} else
return "";
}
}
springmvc.xml配置
<!-- 上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240" />
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1" />
</bean>
controller
接收参数 (HttpServletRequest request, MultipartFile image)
调用图片上传方法
String path = ImageUpload.uploadFile(request, image);
User user = new User();
//path为图片所在路径user.setImage(path);