FastDFS(5):在SpringBoot測試上傳文件到FastDFS

1、首先新建一個SpringBoot Maven 項目

pom 依賴如下

<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.7</version>
</dependency>

2、配置相關規則

/**
 * @ConfigurationProperties:用於讀取yml文件或properties文件的值
 *  其他類可以通過@EnableConfigurationProperties直接加載
 *
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 13:53
 */
@Data
@ConfigurationProperties(prefix = "upload")
@Component
public class UploadProperties {

    private String baseUrl;

    private List<String> allowTypes;

}

3、yml 文件

fdfs:
  so-timeout: 2500       # 讀取時間
  connect-timeout: 600   # 連接超時時間
  thumb-image:           # 縮略圖
    width: 100
    height: 100
  tracker-list:          # tracker 服務地址,可配置多個
    - 391.106.941.239:22122

upload:
  base-url: http://391.106.941.239:900/
  allow-types:          # miniTypes參考:https://www.w3school.com.cn/media/media_mimeref.asp
    - image/jpeg
    - image/png
    - image/bmp
    - image/gif

4、UploadService

/**
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 14:15
 */
@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {


    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UploadProperties uploadProperties;

    public String uploadImage(MultipartFile file) {
        // 1、校驗文件類型
        String contentType = file.getContentType();
        if (!uploadProperties.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件類型不支持");
        }
        // 2、校驗文件內容
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                throw new RuntimeException("上傳文件有問題");
            }
        } catch (IOException e) {
            log.error("校驗文件內容失敗....{}", e);
            throw new RuntimeException("校驗文件內容失敗"+e.getMessage());
        }

        try {
            // 3、上傳到FastDFS
            // 3.1、獲取擴展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上傳
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路徑
            return uploadProperties.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上傳】上傳文件失敗!....{}", e);
            throw  new RuntimeException("【文件上傳】上傳文件失敗!"+e.getMessage());
        }
    }
}

5、UploadController

/**
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 14:27
 */
@RestController
@RequestMapping("upload")
public class UpoadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("/doUpload")
    public Map<String,Object> doUpload(MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        String filePath = uploadService.uploadImage(file);
        map.put("path",filePath);
        return map;
    }

}

6、index.html 測試

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件圖片到fastDFS服務器</title>
</head>
<body>
    <h1>上傳圖片</h1>

    <form action="/upload/doUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上傳">
    </form>

</body>
</html>

7、查看測試結果

在這裏插入圖片描述
返回值:
在這裏插入圖片描述
點擊鏈接即可查看上傳的圖片
在這裏插入圖片描述

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