springboot将MultipartFile放到本地
时间: 2023-10-12 19:03:01 浏览: 199
通过import org.springframework.web.multipart.MultipartFile;上传文件
你可以使用以下代码将Spring Boot中的MultipartFile对象保存到本地:
```java
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
public String saveMultipartFileLocally(MultipartFile multipartFile, String directory) throws IOException {
if (multipartFile.isEmpty()) {
throw new IllegalArgumentException("MultipartFile is empty");
}
if (StringUtils.isEmpty(directory)) {
throw new IllegalArgumentException("Directory path is empty");
}
String fileName = multipartFile.getOriginalFilename();
String filePath = directory + File.separator + fileName;
File file = new File(filePath);
multipartFile.transferTo(file);
return file.getAbsolutePath();
}
```
这段代码中,我们首先检查MultipartFile对象是否为空,然后获取原始文件名并拼接出保存的文件路径。接下来,我们创建一个File对象,并使用transferTo()方法将MultipartFile保存到指定的本地目录中。最后,返回保存文件的绝对路径。
请注意,你需要提供一个合适的目录路径作为参数,确保目录存在并且有足够的权限进行文件保存。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [springboot使用MultipartFile获取上传视频的时长(不用在本地生成临时文件)](https://blog.csdn.net/a116385895/article/details/104990689)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Springboot中MultipartFile的使用](https://blog.csdn.net/weixin_52457750/article/details/128532848)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [springboot环境下将File转换成MultipartFile](https://blog.csdn.net/CS5686/article/details/129209448)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文