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

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



    com.github.tobato
    fastdfs-client
    1.26.5

java fastdfs实现文件(图片)的上传下载_第1张图片

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> 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 map = new HashMap();
        map.put("url", realUrl);
        //设置返回图片的路径
        return Result.ok(map);
    }

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

对上传文件进行测试:

java fastdfs实现文件(图片)的上传下载_第2张图片
java fastdfs实现文件(图片)的上传下载_第3张图片

对下载文件进行测试:

java fastdfs实现文件(图片)的上传下载_第4张图片

看到有图片下载下来了

java fastdfs实现文件(图片)的上传下载_第5张图片

你可能感兴趣的:(Java,java,开发语言)