国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

SpringBoot集成FastDFS依賴(lài)實(shí)現文件上傳的示例

發(fā)布時(shí)間:2021-07-06 11:13 來(lái)源:腳本之家 閱讀:0 作者:niceyoo 欄目: 開(kāi)發(fā)技術(shù)

目錄

前言

對FastDFS文件系統安裝后的使用。

FastDFS的安裝請參考這篇:

本文環(huán)境:IDEA + JDK1.8 + Maven

本文項目代碼:

1、引入依賴(lài)

簡(jiǎn)單說(shuō)一下這個(gè)依賴(lài)部分,目前大部分都是采用的如下依賴(lài):

<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
<dependency>
    <groupId>net.oschina.zcx7878</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27.0.0</version>
</dependency>

本著(zhù)不重復造輪子,且為了使用方便我們可以去GitHub找一個(gè)集成好的依賴(lài):

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

2、將Fdfs配置引入項目

只需要創(chuàng )建一個(gè)配置類(lèi)就可以了:

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class ComponetImport {
    // 導入依賴(lài)組件
}

參考截圖:

3、在application.yml當中配置Fdfs相關(guān)參數

根據自己情況修改相應ip地址及端口號:

server:
  port: 8080

ip: 10.211.55.4 # 根據自己FastDFS服務(wù)器修改

fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image:             #縮略圖生成參數
    width: 150
    height: 150
  tracker-list:            #TrackerList參數,支持多個(gè)
    - 10.211.55.4:22122
  web-server-url: http://${ip}:8888/

4、client封裝工具類(lèi)

創(chuàng )建FastDFSClient.java包裝工具類(lèi),方便后面使用:

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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

@Component
public class FastDFSClient {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上傳文件
     * @param file 文件對象
     * @return 文件訪(fǎng)問(wèn)地址
     * @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 文件訪(fǎng)問(wèn)地址
     * @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);
    }

    /**
     * 將一段字符串生成一個(gè)文件上傳
     * @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 文件訪(fǎng)問(wèn)地址
     * @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) {
            System.out.println(e.getMessage());
            /** TODO 只是測試,所以未使用,logger,正式環(huán)境請修改打印方式 **/
        }
    }
    /**
     * 下載文件
     *
     * @param fileUrl 文件URL
     * @return 文件字節
     * @throws IOException
     */
    public byte[] downloadFile(String fileUrl) throws IOException {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

}

5、創(chuàng )建Conttoler測試類(lèi)

5.1 文件上傳測試

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

    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 上傳
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public String uploadFile(MultipartFile file) throws IOException {
        return fastDFSClient.uploadFile(file);
    }

}

執行效果截圖:

5.2、下載文件測試

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

    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 下載
     * @param fileUrl
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
        byte[] bytes = fastDFSClient.downloadFile(fileUrl);
        /** TODO 這里只是為了整合fastdfs,所以寫(xiě)死了文件格式。需要在上傳的時(shí)候保存文件名。下載的時(shí)候使用對應的格式 **/
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("sb.xlsx", "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

測試下載路徑:

http://127.0.0.1:8080/file/download?fileUrl=group1/M00/00/00/CtM3BF84r4SAEPDgAABoGL78QcY682.jpg

拼接的參數為:group1/M00/00/00/CtM3BF84r4SAEPDgAABoGL78QcY682.jpg

大家想修改路徑的話(huà),需要同步修改 downloadFile() 方法里的分隔方式。

到此這篇關(guān)于SpringBoot集成FastDFS依賴(lài)實(shí)現文件上傳的示例的文章就介紹到這了,更多相關(guān)SpringBoot FastDFS文件上傳內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。

图片小说视频一区二区 | 亚洲SM另类一区二区三区| 日产精品一卡2卡三卡4卡乱码| 一本色道久久99一综合| 亚洲av永久无码国产精品久久| 亚洲精品字幕在线观看|