SpringBoot链接FastDFS并且上传文件

1. 引入Maven相关依赖

<dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
            <exclusions>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-classic</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2.配置配置文件

fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=121.199.2.55:22122
fdfs.web-server-url=http://121.199.2.55/

3.工具类代码

package com.xql.lovebaby.fdfs;
import com.alibaba.druid.util.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author :xql
 * @date :Created in 2021/6/1 下午5:20
 * @description:fdfs注入
 * @modified By:
 * @version: 0.0.1$
 */
@Component
public class FastDFSClient {
    private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    @Resource
    private FastFileStorageClient storageClient;

    @Resource
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream (file);
        StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return getResAccessUrl(storePath);
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 下载文件
     * @param fileUrl 文件url
     * @return
     */
    public byte[]  download(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */

    public void deleteFile(String fileUrl){
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }
}


4.调用

package com.xql.lovebaby.controller;


import com.xql.lovebaby.entity.Photo;
import com.xql.lovebaby.entity.PhotoType;
import com.xql.lovebaby.fdfs.FastDFSClient;
import com.xql.lovebaby.service.PhotoService;
import com.xql.lovebaby.service.PhotoTypeService;
import com.xql.lovebaby.utils.ResultVo;
import com.xql.lovebaby.utils.Utils;
import org.apache.commons.io.IOUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


@RestController
@RequestMapping("/fdfs")
public class FastDFSController {

    @Resource
    private FastDFSClient fdfsClient;

    @Autowired
    private PhotoService photoService;

    @Autowired
    private PhotoTypeService photoTypeService;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("upload")
    @ResponseBody
    public ResultVo upload(MultipartFile file, Photo photo,String typeId) throws Exception{
        if (Utils.isNull(file.getOriginalFilename())){
            return new ResultVo(false,null,"请上传文件");
        }
        String url = fdfsClient.uploadFile(file);
        photoService.insert(url,photo,typeId,file);
        return new ResultVo(true, url,null);
    }

    /**
     * 文件下载
     * @param fileUrl  url 开头从组名开始
     * @param response
     * @throws Exception
     */
    @RequestMapping("download")
    @ResponseBody
    public void  download(String fileUrl, HttpServletResponse response) throws Exception{

        byte[] data = fdfsClient.download(fileUrl);

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8"));

        // 写出
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
    }



    @RequestMapping("my")
    @ResponseBody
    public ModelAndView touploadJsp(HttpServletRequest request){
        ModelAndView mav =new ModelAndView();
        List<Photo> list = photoService.getMy();
        for (int i = 0; i < list.size(); i++) {
            int b = i +1;
            mav.addObject("upload"+b,list.get(i).getPhotoPath());
        }
        Photo photo = photoService.getMys();
        mav.addObject("upload8",photo.getPhotoPath());

        List<PhotoType> photoTypeList = photoTypeService.queryAll();
        mav.addObject("photoTypeList",photoTypeList);
        mav.setViewName("forward:/upload.jsp");
        return mav;
    }

    @RequestMapping("history")
    @ResponseBody
    public ModelAndView history(HttpServletRequest request){
        ModelAndView mav =new ModelAndView();

        mav.setViewName("forward:/history.jsp");
        return mav;
    }
}


上一篇:Codeforces1453F Even Harder


下一篇:Docker + Spring Boot + FastDFS 搭建一套分布式文件服务器,太强了