利用FastDFS实现图片上传功能

1.1.导入maven依赖

        </dependency>
            <dependency>
                <groupId>com.github.tobato</groupId>
                <artifactId>fastdfs-client</artifactId>
            </dependency>
        <dependency>

1.2.编写配置

1.2.1.application.yml

server:
  port: 9999
spring:
  application:
    name: upload-service
  servlet:
    multipart:
      max-file-size: 10MB
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
fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image: # 缩略图
    width: 60
    height: 60
  tracker-list: # tracker地址
    - 192.168.43.66:22122
ly:
  upload:
      baseUrl: http://image.leyou.com/  #静态资源访问路径
      allowTypes:     #允许通过的类型
        - image/png
        - image/jpg
        - image/jpeg

1.2.2要想使用FastDFS首先需要编写个配置类

@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
}

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

1.3.启动类

/**
 * @Auther: The sun is shining
 * @Date:2019/5/26
 * @Description:com.leyou
 * @version:1.0
 */
@EnableDiscoveryClient
@SpringBootApplication
public class LyUpload {

    public static void main(String[] args) {
        SpringApplication.run(LyUpload.class,args);
    }
}

1.4.编写上传功能

1.4.1.controller

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

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

代码如下:

/**
 * @Auther: The sun is shining
 * @Date:2019/5/26
 * @Description:com.leyou.upload.web
 * @version:1.0
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("images")
    public ResponseEntity<String> saveUploadImage(@RequestParam("file") MultipartFile file){


        String url=uploadService.saveUploadImage(file);

        return ResponseEntity.ok(url);
    }
}

1.4.2.service

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

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

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

具体代码:

/**
 * @Auther: The sun is shining
 * @Date:2019/5/26
 * @Description:com.leyou.upload.web.service
 * @version:1.0
 */
@Service
@Slf4j
@EnableConfigurationProperties(LyUploadFastDFSProperties.class)
public class UploadService {


    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private LyUploadFastDFSProperties lyUploadFastDFSProperties;

    public String saveUploadImage(MultipartFile file) {

        //校验文件格式
        if(!lyUploadFastDFSProperties.getAllowTypes().contains(file.getContentType())){
            throw  new RuntimeException("此文件不是图片");
        }
        //校验文件内容
        StorePath storePath;
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            //文件上传到fastDFS
            String exlension= StringUtils.substringAfter(file.getOriginalFilename(),".");
            storePath=storageClient.uploadFile(file.getInputStream(),file.getSize(),exlension,null);

        } catch (IOException e) {
            log.info("此文件不是图片");
            throw  new RuntimeException("此文件不是图片");
        }


        return lyUploadFastDFSProperties.getBaseUrl()+storePath.getFullPath();
    }
}

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

  • 图片不能保存在服务器内部,这样会对服务器产生额外的加载负担
  • 一般静态资源都应该使用独立域名,这样访问静态资源时不会携带一些不必要的cookie,减小请求的数据量
    这里需要注意的是我把静态资源配置到了application.yml
ly:
  upload:
      baseUrl: http://image.leyou.com/  #静态资源访问路径
      allowTypes:     #允许通过的类型
        - image/png
        - image/jpg
        - image/jpeg

这些资源首先要加载到spring容器中我这采用javabean注解方式注入
加入以下代码service中的 LyUploadFastDFSProperties才会被注入

@ConfigurationProperties(prefix = "ly.upload")
@Data
public class LyUploadFastDFSProperties {

    private String baseUrl;
    private List<String> allowTypes;
}

2.2.3.测试上传

我们通过Insomnia工具来测试:

在这里插入图片描述

结果:

在这里插入图片描述

去目录下查看:

在这里插入图片描述在这里插入图片描述

上传成功!

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值