当前位置: 首页> 汽车> 维修 > 【Java】SpringBoot 实现文件的上传与下载、日志记录、参数校验等(含代码示例)

【Java】SpringBoot 实现文件的上传与下载、日志记录、参数校验等(含代码示例)

时间:2025/8/24 3:57:53来源:https://blog.csdn.net/weixin_51484460/article/details/139577964 浏览次数: 0次

在这里插入图片描述

😎 作者介绍:我是程序员洲洲,一个热爱写作的非著名程序员。CSDN全栈优质领域创作者、华为云博客社区云享专家、阿里云博客社区专家博主。
🤓 同时欢迎大家关注其他专栏,我将分享Web前后端开发、人工智能、机器学习、深度学习从0到1系列文章。
🌼 同时洲洲已经建立了程序员技术交流群,如果您感兴趣,可以私信我加入社群,可以直接vx联系(文末有名片)v:bdizztt
🖥 随时欢迎您跟我沟通,一起交流,一起成长、进步!点此也可获得联系方式~

本文目录

  • 前言
  • 一、文件上传与下载
    • 1.1 添加依赖
    • 1.2 配置文件
    • 1.3 文件上传 编写控制器
    • 1.3 文件下载 编写控制器
  • 二、日志记录
    • 2.1 添加依赖
    • 2.2 使用日志
  • 三、参数校验
    • 3.1 使用注解进行校验
    • 3.2 编写控制器并使用校验
  • 四、传统的controller、service、impl层写法
  • 总结

前言

SpringBoot是一个基于Spring框架的快速开发脚手架,它提供了快速集成各种常用功能的能力,比如文件上传下载、日志记录、参数校验等。

本文将通过代码示例实现SpringBoot项目中实现这些功能。

一、文件上传与下载

1.1 添加依赖

首先,需要在pom.xml文件中添加SpringBoot的Web依赖和文件上传依赖:

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
</dependencies>

1.2 配置文件

在application.properties中配置文件上传的大小限制:

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

1.3 文件上传 编写控制器

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;@RestController
public class FileUploadController {@PostMapping("/upload")public String handleFileUpload(@RequestParam("file") MultipartFile file) {if (!file.isEmpty()) {try {// 获取文件名String fileName = file.getOriginalFilename();// 文件处理逻辑,例如保存到服务器上的某个目录// file.transferTo(new File("/path/to/destination/" + fileName));return "You successfully uploaded " + fileName + "!";} catch (Exception e) {return "File upload failed: " + e.getMessage();}} else {return "Please upload a file other than an empty one.";}}
}

1.3 文件下载 编写控制器

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;@RestController
public class FileDownloadController {@GetMapping("/download")public ResponseEntity<byte[]> downloadFile() throws IOException {String fileName = "example.txt"; // 要下载的文件名File file = new File("/path/to/destination/" + fileName);// 将文件转换为字节数组byte[] fileBytes = Files.readAllBytes(file.toPath());// 设置响应的HeaderHttpHeaders headers = new HttpHeaders();headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));// 返回ResponseEntity对象return ResponseEntity.ok().headers(headers).contentLength(fileBytes.length).contentType(MediaType.APPLICATION_OCTET_STREAM).body(fileBytes);}
}

二、日志记录

2.1 添加依赖

在pom.xml中添加日志框架依赖,例如使用SLF4J与Logback:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId>
</dependency>

2.2 使用日志

在类中注入Logger并使用:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class SomeService {private static final Logger logger = LoggerFactory.getLogger(SomeService.class);public void someMethod() {logger.info("some info message");// 其他业务逻辑}
}

三、参数校验

3.1 使用注解进行校验

import javax.validation.constraints.NotBlank;public class SomeDTO {@NotBlank(message = "Name cannot be empty")private String name;// getters and setters
}

3.2 编写控制器并使用校验

import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;@RestController
@Validated
public class SomeController {@PostMapping("/some-endpoint")public String handleSomeRequest(@Valid SomeDTO dto) {// 处理请求return "Request processed successfully";}
}

四、传统的controller、service、impl层写法

@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FileService fileService;// 上传单个文件@PostMapping("/upload")public ResultVo<String> uploadFile(@RequestParam("file") MultipartFile file) {return fileService.uploadFile(file);}}

服务层写法

public interface FileService {// 上传文件ResultVo<String> uploadFile(MultipartFile file);}

FileServiceImpl写法

@Service
@Slf4j
public class FileServiceImpl implements FileService {// 上传文件@Overridepublic ResultVo<String> uploadFile(MultipartFile file) {log.info("【文件上传】进入到文件上传方法");// 1.参数校验if (null == file || file.isEmpty()) {log.error("【文件上传】文件为空!");throw new ParamErrorException();}// 2.上传文件ResultVo<String> resultVo = FileUtil.uploadFile(file);return resultVo;}}

总结

📝Hello,各位看官老爷们好,我已经建立了CSDN技术交流群,如果你很感兴趣,可以私信我加入我的社群。

📝社群中不定时会有很多活动,例如每周都会包邮免费送一些技术书籍及精美礼品、学习资料分享、大厂面经分享、技术讨论谈等等。

📝社群方向很多,相关领域有Web全栈(前后端)、人工智能、机器学习、自媒体副业交流、前沿科技文章分享、论文精读等等。

📝不管你是多新手的小白,都欢迎你加入社群中讨论、聊天、分享,加速助力你成为下一个大佬!

📝想都是问题,做都是答案!行动起来吧!欢迎评论区or后台与我沟通交流,也欢迎您点击下方的链接直接加入到我的交流社群!~ 跳转链接社区~

在这里插入图片描述

关键字:【Java】SpringBoot 实现文件的上传与下载、日志记录、参数校验等(含代码示例)

版权声明:

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

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

责任编辑: