SSM 实现文件上传
时间: 2023-09-12 15:04:33 浏览: 67
SSM(Spring + SpringMVC + MyBatis)是一种常用的Java Web开发框架组合,下面是一个基本的SSM实现文件上传的示例:
1. 首先,在Spring配置文件中添加以下配置:
```
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880"/> <!-- 设置最大上传文件大小 -->
</bean>
```
2. 在Controller中添加处理文件上传的方法:
```java
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 设置文件存储路径
String filePath = "C:/uploads/" + fileName;
// 创建文件对象
File dest = new File(filePath);
// 检查目标目录是否存在,不存在则创建
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 将文件写入目标目录
file.transferTo(dest);
return "upload success";
} catch (IOException e) {
e.printStackTrace();
return "upload failed";
}
} else {
return "file is empty";
}
}
```
3. 在前端页面中添加上传文件的表单:
```html
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
```
当用户选择文件并提交表单时,控制器方法会接收文件并将其保存到指定的目录中。请确保文件上传目录存在并有足够的权限。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)