首先需要导如下jar包:
写个例子upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="book/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file1"/></br>
<input type="submit" value="提交">
<c:if test="${!empty result}">
<li>${result}</li>
</c:if>
</form>
</body>
</html>
然后在springmvc.xml中配置如下bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸20M -->
<property name="maxUploadSize">
<value>20480000</value>
</property>
</bean>
接下来再在控制器BookController.java文件中写
@Controller
@RequestMapping("book")
public class BookController {
@RequestMapping("upload.do")
public String upload(@RequestParam("file1") MultipartFile ft ,HttpServletRequest request){
//图片存储的路径
String path=request.getRealPath("/upload");
//原名称
String filename=ft.getOriginalFilename();
//真实的名称
String real_name=filename.substring(filename.lastIndexOf("/")+1);
//新名称(uuid随机数加上后缀名)
File file=new File(path+"\\"+UUID.randomUUID()+"-"+real_name);
try {
//用transferTo把内存图片写入磁盘中
ft.transferTo(file);
} catch (Exception e) {
e.printStackTrace();
}
//把新的图片写入到对象中,方便数据库中更新
// itemsCustom.setPic(newfileName);
// 调用service更新商品信息,页面需要将商品信息传到此方法
//itemsService.updateItems(id, itemsCustom);
request.setAttribute("result", "上传成功");
return "upload";
}
}
【注】要想@RequestParam(“file1”)注解起作用必须在springmvc.xml中配置bean,这样MultipartFile ft中 ft 才能存放name=”file1”的 input输入框中的上传文件