一. 导入两个jar包
commons-fileupload-1.3.2.jar和commons-io-2.5.jar
二. 创建jsp文件
<form action="/uploadSave" method="post" enctype="multipart/form-data"> <li>文件上传: <input type="file" name="file"> </li> <li> <input type="submit" value="上传"> </li> </form>
三. 创建控制器接收
@Controller
public class UploadController {
@RequestMapping("/upload")
public String upload(){
return "upload";
}
@RequestMapping("/uploadSave")
@ResponseBody
public Map uploadSave(MultipartFile file){
String fileName = file.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf("."));
String newName = UUID.randomUUID() + ext;
//得到新的文件名
String realpath = ResourceBundle.getBundle("config").getString("uppath");
//读取src下config.properties配置上传路径
File targetFile = new File(realpath, newName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
}
Map map = new HashMap<>();
map.put("newName",newName);
return map;
}
}将文件上传至设置目录,并在浏览器显示json格式
{"newName":"984f41e3-14e3-4745-8698-9522fdb06c24.jpg"}在上传文件时需要在配置文件中使用 Spring 的 CommonsMultipartResolver 类配置 MultipartResolver 用于文件上传,应用的配置文件 springmvc-servlet.xml 的代码如下:
<!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000" /> <property name="defaultEncoding" value="UTF-8" /> </bean>
相关:
