• SpringCloud文件上传


    2.实现图片上传

    刚才的新增实现中,我们并没有上传图片,接下来我们一起完成图片上传逻辑。

    文件的上传并不只是在品牌管理中有需求,以后的其它服务也可能需要,因此我们创建一个独立的微服务,专门处理各种上传。

    2.1.搭建项目

    2.1.1.创建SpringCloud项目

    2.1.2.添加依赖

    我们需要EurekaClient和web依赖:

    
    
        
            leyou
            com.leyou.parent
            1.0.0-SNAPSHOT
        
        4.0.0
    
        com.leyou.service
        ly-upload
        1.0.0-SNAPSHOT
    
        
            
                org.springframework.cloud
                spring-cloud-starter-netflix-eureka-client
            
            
                org.springframework.boot
                spring-boot-starter-web
            
            
                org.apache.commons
                commons-lang3
            
            
                org.projectlombok
                lombok
            
        
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    2.1.3.编写配置

    server:
      port: 8082
    spring:
      application:
        name: upload-service
      servlet:
        multipart:
          max-file-size: 5MB # 限制文件上传的大小
    # Eureka
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:10086/eureka
      instance:
        lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
        lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
        prefer-ip-address: true
        ip-address: 127.0.0.1
        instance-id: ${spring.application.name}:${server.port}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    需要注意的是,我们应该添加了限制文件大小的配置

    2.1.4.启动类

    @SpringBootApplication
    @EnableDiscoveryClient
    public class LyUploadService {
        public static void main(String[] args) {
            SpringApplication.run(LyUploadService.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    结构:

    在这里插入图片描述

    2.2.编写上传功能

    2.2.1.controller

    编写controller需要知道4个内容:

    • 请求方式:上传肯定是POST
    • 请求路径:/upload/image
    • 请求参数:文件,参数名是file,SpringMVC会封装为一个接口:MultipleFile
    • 返回结果:上传成功后得到的文件的url路径

    代码如下:

    package com.leyou.upload.web;
    
    import com.leyou.upload.service.UploadService;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    @RestController
    @RequestMapping("upload")
    public class UploadController {
        @Autowired
        private UploadService uploadService;
        /**
         * 上传图片功能
         * @param file
         * @return
         */
        @PostMapping("image")
        public ResponseEntity uploadImage(@RequestParam("file") MultipartFile file){
            String url = uploadService.uploadImage(file);
            if(StringUtils.isBlank(url)){
                // url为空,证明上传失败
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
            // 返回200,并且携带url路径
            return ResponseEntity.ok(url);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    2.2.2.service

    在上传文件过程中,我们需要对上传的内容进行校验:

    1. 校验文件大小
    2. 校验文件的媒体类型
    3. 校验文件的内容

    文件大小在Spring的配置文件中设置,因此已经会被校验,我们不用管。

    具体代码:

    package com.leyou.upload.service;
    
    import com.leyou.common.enums.ExceptionEnum;
    import com.leyou.common.exception.LyException;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.List;
    
    @Service
    @Slf4j
    public class UploadService {
    
        private static final List ALLOW_TYPES = Arrays.asList("image/png", "image/jpeg", "image/bmg");
    
        public String uploadImage(MultipartFile file) {
            try {
                //校验文件类型
                String contentType = file.getContentType();
                if(!ALLOW_TYPES.contains(contentType)){
                    throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
                }
                //校验文件的内容
                BufferedImage image = ImageIO.read(file.getInputStream());
                if(image == null){
                    throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
                }
                //准备目标路径
                File dest = new File("E:\黑马程序员57期\09 微服务电商【黑马乐优商城】\upload\",file.getOriginalFilename());
                file.transferTo(dest);
                //返回路径
                return "http://image.leyou.com/"+file.getOriginalFilename();
            } catch (IOException e) {
                log.error("上传文件失败",e);
                throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    这里有一个问题:为什么图片地址需要使用另外的url?

    • 图片不能保存在服务器内部,这样会对服务器产生额外的加载负担
    • 一般静态资源都应该使用独立域名,这样访问静态资源时不会携带一些不必要的cookie,减小请求的数据量

    2.2.3.测试上传

    我们通过RestClient工具来测试:
    在这里插入图片描述
    结果:
    1526197027688.png
    去目录下查看:
    1526197060729.png
    上传成功!

  • 相关阅读:
    220 - Othello (UVA)
    Mongoose应用和文件上传
    LeetCode[105]从前序与中序遍历序列构造二叉树
    【Pytorch基础】二维/三维情况下 torch.mean()函数使用
    将Abp默认事件总线改造为分布式事件总线
    chatgpt赋能python:Python随机抽取:提高数据样本代表性的利器
    JavaWeb项目(二)
    大型电商网站的异步多级缓存及nginx数据本地化动态渲染架构
    java计算机毕业设计计算机专业招聘网站源码+mysql数据库+系统+lw文档+部署
    java疫情期间社区出入管理系统-计算机毕业设计源码21295
  • 原文地址:https://blog.csdn.net/m0_52789121/article/details/126516377