用SpringMVC框架编程实现图片文件上传。
时间: 2024-02-12 20:09:46 浏览: 75
好的,下面是用SpringMVC框架实现图片文件上传的步骤:
1. 在pom.xml文件中加入以下依赖:
```xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
```
2. 在spring配置文件中加入以下配置:
```xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
</bean>
```
其中,maxUploadSize属性是上传文件的最大大小,单位为字节。上面的配置表示最大上传5MB的文件。
3. 在Controller中添加以下方法:
```java
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/" + fileName;
File dest = new File(filePath);
file.transferTo(dest);
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
} else {
return "文件为空";
}
}
```
其中,@RequestParam注解表示获取上传的文件,MultipartFile类型表示文件类型。
4. 在JSP页面中添加以下代码:
```jsp
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
```
其中,enctype属性表示表单数据的编码类型,必须设置为multipart/form-data,才能支持文件上传。
以上就是用SpringMVC框架实现图片文件上传的完整步骤。
阅读全文
相关推荐


















