所需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();
user.setImage(path);//path爲圖片所在路徑