首頁 > 軟體

Java實現整合檔案上傳到FastDFS的方法詳細

2022-02-26 19:03:04

1.引入fastdfs依賴到pom.xml

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

2.上傳程式碼如下

上傳純檔案流

    /**
     * 檔案上傳
     * @param file MultipartFile型別
     * @return url
     */
    @Override
    public String fileUpload(MultipartFile file) throws Exception {
        try {
            return upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
    }

上傳網路資源連結:

    /**
     * 檔案上傳
     * @param urlStr url地址
     * @return url
     */
    @Override
    public String fileUpload(String urlStr) throws Exception {
        try {
            //把地址轉換成URL物件
            URL url = new URL(urlStr);
            //建立http連結
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //設定超時間為3秒
            conn.setConnectTimeout(3*1000);
            //防止遮蔽程式抓取而返回403錯誤
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
            //得到輸入流
            InputStream inputStream = conn.getInputStream();
            //擷取連結中的檔名
            String fileName= urlStr.substring(urlStr.lastIndexOf("/")+1);
            MultipartFile multipartFile = new MockMultipartFile(fileName,fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            //返回結果集
            return upload(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
 
    }

整體程式碼如下:

package com.tfjybj.arpro.crawl.service.impl;
 
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tfjybj.arpro.crawl.service.FileUploadService;
import com.tfjybj.arpro.crawl.util.CommonConfigurationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
 * 檔案上傳業務類
 *
 * @author Promsing(張有博)
 * @version 1.0.0
 * @since 2022/2/25 - 20:01
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
 
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
 
 
    // 獲取組態檔中的設定IP地址
    @Value("${fdfs.realIp}")
    private String realIp;
    // 獲取組態檔中的設定分組
    @Value("${fdfs.groupName}")
    private String group;
 
 
 
    /**
     * 檔案上傳
     * @param file MultipartFile型別
     * @return url
     */
    @Override
    public String fileUpload(MultipartFile file) throws Exception {
        try {
            return upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
    }
 
    /**
     * 檔案上傳
     * @param urlStr url地址
     * @return url
     */
    @Override
    public String fileUpload(String urlStr) throws Exception {
        try {
            //把地址轉換成URL物件
            URL url = new URL(urlStr);
            //建立http連結
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //設定超時間為3秒
            conn.setConnectTimeout(3*1000);
            //防止遮蔽程式抓取而返回403錯誤
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
            //得到輸入流
            InputStream inputStream = conn.getInputStream();
            //擷取連結中的檔名
            String fileName= urlStr.substring(urlStr.lastIndexOf("/")+1);
            MultipartFile multipartFile = new MockMultipartFile(fileName,fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            //返回結果集
            return upload(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
 
    }
 
    /**
     * 檔案上傳
     * @param file 需要上傳的檔案
     * @return 上傳後的檔案地址
     */
    public String upload(MultipartFile file) {
        try {
            // 1.檔案資訊校驗
            if (file.isEmpty()) {
                log.debug("需要上傳的檔案資訊不通過");
                return null;
            }
            // 2.儲存圖片到fastDFS伺服器
            //2.1 獲取檔案字尾名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //2.2 儲存
            StorePath storePath = fastFileStorageClient.uploadFile(group, file.getInputStream(), file.getSize(), extension);
            // 獲取附件的完整地址
            String Path = CommonConfigurationUtil.HTTP + CommonConfigurationUtil.ECOLON + CommonConfigurationUtil.DOUBLE_SLASH + realIp + CommonConfigurationUtil.SINGLE_SLASH + storePath.getFullPath();
            log.info("檔案上傳成功,檔案地址:" + Path);
            return Path;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
 
}

3.組態檔如下

# 檔案伺服器基礎設定
fdfs:
  groupName: ar
  so-timeout: 1500
  connect-timeout: 600
  tracker-list: d-fastdfs.xxxx.com:22122
  replace-ip:
    source: d-fastdfs.xxxx.com
    dest: d-fastdfs.xxxx.com
  realIp: d-fastdfs.xxxx.com

4.上傳效果如下

無論是純檔案上傳還是以網路資源連結的形式上傳都是檔案流上傳的形式。

到此這篇關於Java實現整合檔案上傳到FastDFS的方法詳細的文章就介紹到這了,更多相關Java檔案上傳FastDFS內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com