SpringBoot 上传文件功能
注意事项:
springboot默认有以下文件配置要求, 可以自行在配置文件里面修改
spring:
servlet:
multipart:
enabled: true #是否处理上传
max-file-size: 1MB #允许最大的单个上传大小,单位可以是kb
max-request-size: 10MB #允许最大请求大小
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.util.UUID; @Controller public class FileUploadController { /** * 因为最终项目会打成jar包,所以这个的路径不能是jar包里面的路径 * 可以使用其他路径,比如上传到F盘下的upload文件夹下 写成:F:/upload/ */ private String fileUploadPath = ""; /** * 文件上传,具体逻辑可以自行完善 * * @param file 前端表单的name名 * @return w */ @PostMapping("/upload") @ResponseBody public String upload(MultipartFile file) { if (file.isEmpty()) { //文件空了 return null; } //文件扩展名 String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //使用UUID生成文件名称 String fileName = UUID.randomUUID().toString() + extName; //文件上传的全路径 String filePath = fileUploadPath + fileName; File toFile=new File(filePath); if (!toFile.getParentFile().exists()){ //文件夹不存在,先创建文件夹 toFile.getParentFile().mkdirs(); } try { //进行文件复制上传 FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile)); } catch (Exception e) { //上传失败 e.printStackTrace(); } //返回文件所在绝对路径 return filePath; } }
然后添加个配置就可以把路径映射出去
@Configuration public class webMvcConfigurerAdapter implements WebMvcConfigurer { /** * 配置静态访问资源 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/file/**").addResourceLocations("classpath:/path/"); } }
- addResoureHandler:指的是对外暴露的访问路径
- addResourceLocations:指的是内部文件放置的目录(如果在项目下 可以配置成 file:/path/)
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了