欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Spring Boot文件上传

Spring Boot文件上传

2025/2/23 10:21:47 来源:https://blog.csdn.net/qq_59636442/article/details/142432917  浏览:    关键词:Spring Boot文件上传

配置文件上传属性:

在application.properties文件中配置文件上传的属性,包括上传目录的路径、文件大小限制等。

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

处理文件上传请求

上传的文件按照日期进行归类,使用UUID给文件重命名

    @PostMapping("/upload/")@ResponseBodypublic  Response upload(MultipartFile file) {// 验证是否有文件if(file == null || file.isEmpty()){return Response.newFail("Upload failed, please select file",400);}// 文件保存目录SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");String format = sdf.format(new Date());String filePath = "D:/flies/springboot/"+format;// 验证文件夹File folder = new File(filePath);if (!folder.exists()) {folder.mkdirs();}// 文件名String fileName = UUID.randomUUID() + file.getOriginalFilename();filePath = filePath  + fileName;File saveFile = new File(filePath);try {file.transferTo(saveFile);return  Response.newSuccess("Upload successful");} catch (IOException e) {e.printStackTrace();return  Response.newFail("Upload failed",50001);}}

文件过大

如果遇到文件过大出现413状态码无结果
需要统一返回json,可以参考
Springboot封装统一返回结果及全局异常处理

配置文件保存路径

可以在配置中保存文件的存放位置,方便更改

配置文件

application.properties文件添加需要的配置

file.path=D:\\flies\\springboot\\

@ConfigurationProperties 注解

使用注解@ConfigurationProperties将配置项和实体Bean关联起来,实现配置项和实体类字段的关联,读取配置文件数据。

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileConfig {private String path;
}

使用

获取配置信息

FileConfig fileConfig = new FileConfig();
// 文件保存目录
String filePath = fileConfig.getPath();
    @PostMapping("/upload/")@ResponseBodypublic  Response upload(MultipartFile file) {// 验证是否有文件if(file == null || file.isEmpty()){return Response.newFail("Upload failed, please select file",400);}FileConfig fileConfig = new FileConfig();// 文件保存目录String filePath = fileConfig.getPath();// 验证文件夹File folder = new File(filePath);if (!folder.exists()) {folder.mkdirs();}// 文件名String fileName = UUID.randomUUID() + file.getOriginalFilename();filePath = filePath  + fileName;File saveFile = new File(filePath);try {file.transferTo(saveFile);return  Response.newSuccess("Upload successful");} catch (IOException e) {e.printStackTrace();return  Response.newFail("Upload failed",50001);}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词