一、设置好form表单格式
二、在springmvc.xml中设置解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设定默认编码 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 设定文件上传的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880"></property> </bean>
三、如果配置的springmvc的url映射为/即
<url-pattern>/</url-pattern>
此时会对所有路径进行解析,因此我们需要在springmvc.xml中对静态资源进行设置
<!-- 资源映射 --> <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/upload/" mapping="/upload/**"/>
四、上传图片
@RequestMapping("/pic/upload") @ResponseBody public String uploadFile(MultipartFile uploadFile, HttpServletRequest request) { String path = request.getSession().getServletContext().getRealPath("WEB-INF/upload"); String oldName = uploadFile.getOriginalFilename();
String newName = IDUtils.genImageName();
newName = newName + oldName.substring(oldName.lastIndexOf("."));
try {
uploadFile.transferTo(new File(basePath, newName));
} catch (Exception e) {
//todo
}
return "result"; }
public class IDUtils { /** * 图片名生成 */ public static String genImageName() { //取当前时间的长整形值包含毫秒 long millis = System.currentTimeMillis(); //long millis = System.nanoTime(); //加上三位随机数 Random random = new Random(); int end3 = random.nextInt(999); //如果不足三位前面补0 String str = millis + String.format("%03d", end3); return str; } /** * 商品id生成 */ public static long genItemId() { //取当前时间的长整形值包含毫秒 long millis = System.currentTimeMillis(); //long millis = System.nanoTime(); //加上两位随机数 Random random = new Random(); int end2 = random.nextInt(99); //如果不足两位前面补0 String str = millis + String.format("%02d", end2); long id = new Long(str); return id; } public static void main(String[] args) { for(int i=0;i< 100;i++) System.out.println(genItemId()); } }
访问路径:http://localhost:8080/upload/1462075625990243.png
另外ajax上传写法见:
http://www.cnblogs.com/tuifeideyouran/p/4641188.html