SpringMVC上传文件

SpringMVC配置文件:

 1 <bean id="multipartResolver"  
 2         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
 3         <!-- 上传文件大小上限,单位为字节(10MB) -->
 4         <property name="maxUploadSize">  
 5             <value>10485760</value>  
 6         </property>  
 7         <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
 8         <property name="defaultEncoding">
 9             <value>UTF-8</value>
10         </property>
11     </bean>

前端:

 1 <form action="upload" enctype="multipart/form-data" method="post">
 2         <table>
 3             <tr>
 4                 <td>文件描述:</td>
 5                 <td><input type="text" name="description"></td>
 6             </tr>
 7             <tr>
 8                 <td>请选择文件:</td>
 9                 <td><input type="file" name="file"></td>
10             </tr>
11             <tr>
12                 <td><input type="submit" value="上传"></td>
13             </tr>
14         </table>
15     </form>

Controller:

 1 @RequestMapping(value="upload",method = RequestMethod.POST)
 2     @ResponseBody
 3     public String upload(@RequestParam("file")MultipartFile mf, HttpServletRequest request) {
 4         JSONObject json = new JSONObject();
 5         json.put("code", 0);
 6         json.put("msg", "上传图片成功!请编辑并保存模板。");
 7         String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
 8         String path = request.getServletContext().getRealPath("upload");
 9         File file = new File(path, uuid + mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf('.')));
10         json.put("data", file.getName());
11         //上传文件
12         try {
13             mf.transferTo(file);
14         } catch (IllegalStateException | IOException e) {
15             e.printStackTrace();
16             json.put("code", -1);
17             json.put("msg", e.getMessage());
18         }
19         return json.toString();
20     }
原文地址:https://www.cnblogs.com/guanghe/p/9396827.html