ssm框架多图片上传代码
时间: 2023-06-23 07:09:20 浏览: 121
首先,需要在前端页面中设置一个文件上传的表单,可以使用HTML中的input标签来实现:
```html
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple"/>
<input type="submit" value="上传"/>
</form>
```
其中,`enctype="multipart/form-data"`表示使用多媒体表单进行数据提交,`input`标签中的`name`属性必须为`file`,`multiple="multiple"`表示可以一次上传多个文件。
然后,在后台的Controller中添加对应的处理方法:
```java
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1. 获取上传的文件
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartHttpServletRequest.getFile("file");
// 2. 设置保存路径
String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
File saveFile = new File(savePath);
if (!saveFile.exists()) {
saveFile.mkdir();
}
// 3. 写入文件
String filename = file.getOriginalFilename();
File destFile = new File(savePath + filename);
if (!destFile.exists()) {
destFile.createNewFile();
}
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
// 4. 返回结果
return "上传成功!";
}
```
其中,`MultipartHttpServletRequest`用于处理多媒体请求,`getFile("file")`方法用于获取上传的文件。`getRealPath("/")`方法获取当前Web应用的根目录,`FileUtils.copyInputStreamToFile()`方法用于将上传的文件写入磁盘中。
最后,需要在`springmvc.xml`中配置文件上传的相关Bean:
```xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="2097152"/>
</bean>
```
其中,`CommonsMultipartResolver`是SpringMVC中默认的文件上传解析器,`maxUploadSize`属性用于设置最大上传文件大小。
阅读全文
相关推荐















