springboot2.x整合fastDfs

如果需要自己搭建文件服務器請移步:fastDfs安裝配置教程

springboot整合fastDfs

  • pom.xml添加配置
        <!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.6</version>
        </dependency>
  • application.yml配置
project:
    ## 文件服務器域名
    fastDfsUrl: http://39.96.46.193/
fdfs:
  #鏈接超時
  connect-timeout: 2000
  # 讀取時間
  so-timeout: 2000
  thumb-image:  #生成縮略圖參數
    width: 150
    height: 150
  tracker-list: 39.96.46.193:22122
  • fastdfs配置類
package com.hanergy.out.config;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

@Configuration
@Import(FdfsClientConfig.class)
// Jmx重複註冊bean的問題
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DfsConfig {
}
  • fastDfs工具類
package com.hanergy.out.utils;

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 org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;


@Component
@PropertySource("classpath:application.yml")
public class FileDfsUtils {

    private static final Logger log = LoggerFactory.getLogger(FileDfsUtils.class);

    @Value("${project.fastDfsUrl}")
    private String fastDfsUrl;

    @Autowired
    private FastFileStorageClient storageClient ;
    /**
     * 上傳圖片 會自動裁剪(這裏文件不是圖片會報異常)
     */
    public String uploadImage(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
        return fastDfsUrl + storePath.getFullPath() ;
    }

    /**
     * 上傳文件(通用)
     */
    public String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadFile( multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
//                uploadImageAndCrtThumbImage(
//                multipartFile.getInputStream(),
//                multipartFile.getSize(),originalFilename , null);
        return fastDfsUrl + storePath.getFullPath() ;
    }
    /**
     * @Description: 根據文件路徑下載文件
     * @param filePath 文件路徑
     * @return 文件字節數據
     * @throws Exception byte[]
     */
    public byte[] downFile(String filePath) throws Exception {
        StorePath storePath = StorePath.parseFromUrl(filePath);

        return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadCallback<byte[]>() {
            @Override
            public byte[] recv(InputStream ins) throws IOException {
                return IOUtils.toByteArray(ins);
            }
        });
    }

    /**
     * 刪除文件
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.info("fileUrl == >>文件路徑爲空...");
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}

  • controller代碼
package com.hanergy.out.controller;

import com.hanergy.out.utils.FileDfsUtils;
import com.hanergy.out.utils.R;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileManageController {

    @Autowired
    private FileDfsUtils fileDfsUtils;



    /**
     * 文件上傳
     */
    @ApiOperation(value="上傳文件", notes="測試FastDFS文件上傳")
    @PostMapping(value = "/uploadFile",headers="content-type=multipart/form-data")
    public R uploadFile (@RequestParam("file") MultipartFile file){
        String result ;
        try{
            String path = fileDfsUtils.upload(file);
            if (!StringUtils.isEmpty(path)){
                result = path ;
            } else {
                result = "上傳失敗" ;
            }
        } catch (Exception e){
            e.printStackTrace() ;
            result = "服務異常" ;
        }
        return R.ok(1,result);
    }

    @GetMapping("/download")
    public void downFile(@RequestParam("url") String url,HttpServletResponse response) throws Exception {
        byte[] bytes = fileDfsUtils.downFile(url);
        //設置相應類型application/octet-stream        (注:applicatoin/octet-stream 爲通用,一些其它的類型蘋果瀏覽器下載內容可能爲空)
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //設置頭信息                 Content-Disposition爲屬性名  附件形式打開下載文件   指定名稱  爲 設定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("123.png", "UTF-8"));
        // 寫入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();

    }
}

至此 開發完成,可以用postman調用接口測試文件上傳了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章