springboot 文件上传、配置文件大小、图片展示、全局异常处理

作为Java-web,平时总会在项目中涉及到文件上传,比如图片上传、Excel上传、PDF上传等等情况,今天以最普遍的图片上传为例,展示如下:

pom.xml
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--  第三方工具类 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.12.0</version>
		</dependency>
	</dependencies>
application.yml
server:
  port: 6060
 # 图片存储地址
img:
  location: C:/Download

spring:
  servlet:
    multipart:
      enabled: true
      # 设置单文件最大值
      max-file-size: 2MB
      # 设置单次请求文件最大值
      max-request-size: 10MB
  # 设置文件预览路径
  resources:
    static-locations: file:${img.location}
业务逻辑
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${img.location}")
    private String imgLocation;

    @Value("${spring.servlet.multipart.max-file-size}")
    private String imgSize;


    @PostMapping("/img")
    public String uploadImg(@RequestParam("logo") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        FileOutputStream fileOutputStream = null;
        String newFileName = null;
        if (file != null) {
            //获取文件原始文件名
            String filename = file.getOriginalFilename();
            if (StringUtils.isNotBlank(filename)) {

                String[] filenameArr = filename.split("\\.");
                //  获取文件后缀名
                String suffix = filenameArr[filenameArr.length - 1];
                // 判断图片格式,判断时忽略大小写
                if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                    throw new RuntimeException("图片格式不正确");
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
                // 文件名重组  logo-uuid()随机字符-时间
                newFileName = "logo-" + UUID.randomUUID() + date + "." + suffix;

                // 图片最终保存位置  路径 + 文件名
                String finalFilePath = imgLocation + File.separator + newFileName;
                System.out.println(finalFilePath);
                // 上传文件
                File outFile = new File(finalFilePath);
                // 判断文件夹是否存在
                if (outFile.getParentFile() != null) {
                    // 创建文件夹
                    outFile.getParentFile().mkdirs();
                }
                // 文件输出保存到文件夹
                fileOutputStream = new FileOutputStream(outFile);
                InputStream inputStream = file.getInputStream();

                IOUtils.copy(inputStream, fileOutputStream);
            }
        } else {
            throw new RuntimeException("文件不能为空");
        }
        return "图片上传成功:查看地址为:ip:port" + newFileName;
    }

    private long parseSize(String size) {
        size = size.toUpperCase();
        return size.endsWith("KB")?Long.valueOf(size.substring(0, size.length() - 2)).longValue() * 1024L:(size.endsWith("MB")?Long.valueOf(size.substring(0, size.length() - 2)).longValue() * 1024L * 1024L:Long.valueOf(size).longValue());
    }
}
全局异常类
/**
 * @Description: 设置全局异常类,捕获异常
 *  全局异常类,是在Controller执行之前被调用的
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    //单独捕获 文件上传过大的异常,可以配合 使用统一返回对象RestUtil(code,msg,data) 进行指定错误码、错误消息内容等
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public String Exception(MaxUploadSizeExceededException e) {
        return "上传文件过大,不得超过2MB";
        //return e.getMessage();
    }

}
通过postman测试

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值