引入jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
前台
<form action="/fileUpload" method="post" enctype="multipart/form-data">
名称:<input type="text" name="picname"/><br/>
图片:<input type="file" multiple name="uploadFile"/><br/>
<input type="submit" value=" 上传 "/>
</form>
java后台
@Controller("fileUpload")
public class Upload {
@RequestMapping("/fileUpload")
public String fileUpload(String picname,
MultipartFile uploadFile,
HttpServletRequest request) throws Exception {
String fileName = "";
String uploadName = uploadFile.getOriginalFilename();
System.out.println(uploadName);
String extendName = uploadName.substring(uploadName.lastIndexOf(".")+1,
uploadName.length());
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
if(!StringUtils.isEmpty(picname)) {
fileName = uuid+"_"+picname+"."+extendName;
}else {
fileName = uuid+"_"+uploadName;
}
System.out.println(fileName);
ServletContext context = request.getServletContext();
String basePath = context.getRealPath("/uploads");
System.out.println(basePath);
String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
File file = new File(basePath+"/"+datePath);
if(!file.exists()) {
file.mkdirs();
}
uploadFile.transferTo(new File(file,fileName));
return "success11";
}
}