java fastdfs实现文件(图片)的上传下载

1、首先引入依赖、目录结构:

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

在这里插入图片描述

2、在application.yml中添加如下配置

spring:
  profiles:
    active: dev
---
server:
  port: 9005
spring:
  application:
    name: leadnews-dfs
  profiles: dev
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.211.136:3306/leadnews_article?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

  cloud:
    nacos:
      server-addr: 192.168.211.136:8848
      discovery:
        server-addr: ${spring.cloud.nacos.server-addr}
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
# fastdfs的配置(主要是下边这些配置)
fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:
    - 192.168.211.136:22122 #TrackerList参数,支持多个
  web-server-url: http://192.168.211.136/  # 设置前缀路径
logging:
  level.com: info

3、编写启动类

package com.jjw;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class DfsApplication {
        public static void main(String[] args) {
            SpringApplication.run(DfsApplication.class, args);
        }
}

4、编写controller类实现文件的上传下载功能

package com.jjw.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.jjw.dfs.dto.DownUrl;
import com.jjw.result.pojo.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dfs")
public class FileController {


    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> upload(MultipartFile file) throws Exception {
        StorePath storePath = fastFileStorageClient.uploadFile(
                file.getInputStream(),
                file.getSize(),
                StringUtils.getFilenameExtension(file.getOriginalFilename()),
                null
        );
        String fullPath = storePath.getFullPath();
        String realUrl = fdfsWebServer.getWebServerUrl() + fullPath;
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", realUrl);
        //设置返回图片的路径
        return Result.ok(map);
    }

    @PostMapping("/download")
    public Result download(@RequestBody DownUrl downUrl) throws Exception {
        String uploadFile = downUrl.getUploadFile();
        List<String> list = Arrays.asList(uploadFile.split("/"));
        String groupName = list.get(1);
        String fileName = list.get(list.size() - 1);
        List<String> list1 = Arrays.asList(uploadFile.split("/" + groupName+"/"));
        String localPalace = list1.get(list1.size() - 1);
        byte[] group1s = fastFileStorageClient.downloadFile(groupName, localPalace, new DownloadCallback<byte[]>() {
            @Override
            public byte[] recv(InputStream ins) throws IOException {

                //获取字节数组
                byte[] bytes = IOUtils.toByteArray(ins);
                return bytes;
            }
        });

        String downloadPlace = downUrl.getDownloadPlace();
        //下载
        FileOutputStream fileOutputStream = new FileOutputStream(new File(downloadPlace+"/"+fileName));
        fileOutputStream.write(group1s);
        fileOutputStream.close();
        return Result.ok();
    }
}

DownUrl中的内容:

package com.jjw.dfs.dto;

import lombok.Data;

@Data
public class DownUrl {
    private String downloadPlace;
    private String uploadFile;
}

对上传文件进行测试:

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

对下载文件进行测试:

在这里插入图片描述

看到有图片下载下来了

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值