• FastDFS基础学习(三)之使用FastDFS


    Java上传文件

    首先拉取最新的FastDFS代码

    GitHub - wangwei216/fastdfs-client-java-master

    打包到本地

    mvn clean install

    更换jdk版本  

            

            1.6

            

            1.8

    新建一个springboot项目

     创建一个controller用来进行测试

    1. @RestController
    2. @RequestMapping("/fdfs")
    3. public class FdfsController {
    4. @GetMapping(value = "/hello")
    5. public String hello(){
    6. return "桃李不言下";
    7. }
    8. }
    配置文件启动端口修改一下
    server.port=8090
    pom.xml文件
    1. <properties>
    2. <java.version>1.8java.version>
    3. <fastjson.version>1.2.75fastjson.version>
    4. <hutool.version>5.5.2hutool.version>
    5. <generator.version>1.1.2generator.version>
    6. <commons-io.version>2.8.0commons-io.version>
    7. <commons-lang3.version>3.11commons-lang3.version>
    8. properties>
    9. <dependencies>
    10. <dependency>
    11. <groupId>org.springframework.bootgroupId>
    12. <artifactId>spring-boot-starter-webartifactId>
    13. dependency>
    14. <dependency>
    15. <groupId>org.springframework.bootgroupId>
    16. <artifactId>spring-boot-starter-webfluxartifactId>
    17. dependency>
    18. <dependency>
    19. <groupId>org.springframework.sessiongroupId>
    20. <artifactId>spring-session-coreartifactId>
    21. dependency>
    22. <dependency>
    23. <groupId>org.springframework.bootgroupId>
    24. <artifactId>spring-boot-devtoolsartifactId>
    25. <scope>runtimescope>
    26. <optional>trueoptional>
    27. dependency>
    28. <dependency>
    29. <groupId>org.springframework.bootgroupId>
    30. <artifactId>spring-boot-configuration-processorartifactId>
    31. <optional>trueoptional>
    32. dependency>
    33. <dependency>
    34. <groupId>org.projectlombokgroupId>
    35. <artifactId>lombokartifactId>
    36. <optional>trueoptional>
    37. dependency>
    38. <dependency>
    39. <groupId>org.springframework.bootgroupId>
    40. <artifactId>spring-boot-starter-tomcatartifactId>
    41. <scope>providedscope>
    42. dependency>
    43. <dependency>
    44. <groupId>org.springframework.bootgroupId>
    45. <artifactId>spring-boot-starter-testartifactId>
    46. <scope>testscope>
    47. dependency>
    48. <dependency>
    49. <groupId>io.projectreactorgroupId>
    50. <artifactId>reactor-testartifactId>
    51. <scope>testscope>
    52. dependency>
    53. <dependency>
    54. <groupId>cn.hutoolgroupId>
    55. <artifactId>hutool-allartifactId>
    56. <version>${hutool.version}version>
    57. dependency>
    58. <dependency>
    59. <groupId>com.github.binarywanggroupId>
    60. <artifactId>java-testdata-generatorartifactId>
    61. <version>${generator.version}version>
    62. dependency>
    63. <dependency>
    64. <groupId>commons-iogroupId>
    65. <artifactId>commons-ioartifactId>
    66. <version>${commons-io.version}version>
    67. dependency>
    68. <dependency>
    69. <groupId>com.alibabagroupId>
    70. <artifactId>fastjsonartifactId>
    71. <version>${fastjson.version}version>
    72. dependency>
    73. <dependency>
    74. <groupId>org.apache.commonsgroupId>
    75. <artifactId>commons-lang3artifactId>
    76. <version>${commons-lang3.version}version>
    77. dependency>
    78. <dependency>
    79. <groupId>org.csourcegroupId>
    80. <artifactId>fastdfs-client-javaartifactId>
    81. <version>1.29-SNAPSHOTversion>
    82. dependency>
    83. <exclusions>
    84. <exclusion>
    85. <groupId>org.slf4jgroupId>
    86. <artifactId>slf4j-log4j12artifactId>
    87. exclusion>
    88. exclusions>
    89. dependencies>
    90. <build>
    91. <plugins>
    92. <plugin>
    93. <groupId>org.springframework.bootgroupId>
    94. <artifactId>spring-boot-maven-pluginartifactId>
    95. <version>2.5.10version>
    96. plugin>
    97. plugins>
    98. build>

     resources下fastdfs-client.properties

    1. #连接超时时间,单位为秒。
    2. fastdfs.connect_timeout_in_seconds = 5
    3. #通信超时时间,单位为秒。发送或接收数据时。假设在超时时间后还不能发送或接收数据,则本次网络通信失败
    4. fastdfs.network_timeout_in_seconds = 30
    5. #charset: 字符集
    6. fastdfs.charset = UTF-8
    7. fastdfs.http_anti_steal_token = false
    8. fastdfs.http_secret_key = FastDFS1234567890
    9. #tracker的http端口
    10. fastdfs.http_tracker_http_port = 28083
    11. #tracker服务器IP和端口设置
    12. fastdfs.tracker_servers = 39.97.100.141:22122
    13. fastdfs.connection_pool.enabled = true
    14. fastdfs.connection_pool.max_count_per_entry = 500
    15. fastdfs.connection_pool.max_idle_time = 3600
    16. fastdfs.connection_pool.max_wait_time_in_ms = 1000

    application.yml

    1. server:
    2. port: 8090
    3. spring:
    4. servlet:
    5. multipart:
    6. max-file-size: 50MB #文件上传大小限制为
    7. max-request-size: 200MB #请求大小限制为
    8. #查看图片的端口号
    9. fdfs_storage_proxy:
    10. protocol: http://
    11. domain: 192.168.178.130
    12. port: 8888

     测试

    1. import org.springframework.beans.factory.annotation.Value;
    2. import org.springframework.web.bind.annotation.GetMapping;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import org.springframework.web.bind.annotation.RestController;
    5. @RestController
    6. @RequestMapping("/fdfs")
    7. public class FdfsController {
    8. @Value("${fdfs_storage_proxy.protocol}")
    9. private String fdfs_storage_proxy_protocol;
    10. @Value("${fdfs_storage_proxy.domain}")
    11. private String fdfs_storage_proxy_domain;
    12. @Value("${fdfs_storage_proxy.port}")
    13. private String fdfs_storage_proxy_port;
    14. @GetMapping("/proxy")
    15. public String proxy(){
    16. return fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port;
    17. }
    18. @GetMapping(value = "/hello")
    19. public String hello(){
    20. return "桃李不言下";
    21. }
    22. }

    返回值状态枚举

    ResultCode.enum
    1. /*
    2. * 返回值状态枚举
    3. * */
    4. public enum ResultCode {
    5. /*
    6. * 操作成功 请求成功
    7. * */
    8. SUCCESS("200","操作成功","请求成功"),
    9. /*
    10. * 上传失败
    11. * */
    12. UPLOAD_FAILED("700","上传失败","上传失败");
    13. /*
    14. * 状态码
    15. * */
    16. private String code;
    17. /*
    18. * 状态码含义
    19. * */
    20. private String msg;
    21. /*
    22. * 状态码含义描述
    23. * */
    24. private String desc;
    25. ResultCode(String code,String msg,String desc){
    26. this.code=code;
    27. this.msg=msg;
    28. this.desc=desc;
    29. }
    30. public String getCode() {
    31. return code;
    32. }
    33. public String getMsg() {
    34. return msg;
    35. }
    36. public String getDesc() {
    37. return desc;
    38. }
    39. public void setCode(String code) {
    40. this.code = code;
    41. }
    42. public void setMsg(String msg) {
    43. this.msg = msg;
    44. }
    45. public void setDesc(String desc) {
    46. this.desc = desc;
    47. }
    48. }
    R.java
    1. /*
    2. * 统一返回数据格式
    3. * */
    4. @NoArgsConstructor
    5. @AllArgsConstructor
    6. @Getter
    7. @Setter
    8. public class R{
    9. /*
    10. * 状态码
    11. * */
    12. private String code;
    13. /*
    14. * 状态码含义
    15. * */
    16. private String msg;
    17. /*
    18. * 状态码含义描述
    19. * */
    20. private T data;
    21. }
    FdfsController.java
    1. @RestController
    2. @RequestMapping("/fdfs")
    3. public class FdfsController {
    4. @Value("${fdfs_storage_proxy.protocol}")
    5. private String fdfs_storage_proxy_protocol;
    6. @Value("${fdfs_storage_proxy.domain}")
    7. private String fdfs_storage_proxy_domain;
    8. @Value("${fdfs_storage_proxy.port}")
    9. private String fdfs_storage_proxy_port;
    10. @GetMapping("/proxy")
    11. public String proxy(){
    12. return fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port;
    13. }
    14. @GetMapping(value = "/hello")
    15. public String hello(){
    16. return "桃李不言下";
    17. }
    18. @RequestMapping("/upload1")
    19. public R<String>update01(@RequestParam("header")MultipartFile multipartFile){
    20. //封装返回数据 默认为上传失败
    21. R<String> response = new R<>(ResultCode.UPLOAD_FAILED.getCode(), ResultCode.UPLOAD_FAILED.getMsg(), null);
    22. //获取原文件的名字
    23. String originalFilename = multipartFile.getOriginalFilename();
    24. //获取源文件后缀名
    25. String suffix = FilenameUtils.getExtension(originalFilename);
    26. //文件上传
    27. try {
    28. //加载fastdfs-client.properties配置文件
    29. ClientGlobal.initByProperties("fastdfs-client.properties");
    30. //获取tracker和storage客户端对象
    31. TrackerClient client = new TrackerClient();
    32. //获取tracker地址
    33. TrackerServer trackerServer = client.getTrackerServer();
    34. StorageServer storageServer=null;
    35. //获取storage地址
    36. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    37. //文件上传字节数组
    38. InputStream inputStream = multipartFile.getInputStream();
    39. int length = inputStream.available();
    40. byte[] bytes = new byte[length];
    41. //文件上传成功后重新封装返回数据
    42. inputStream.read(bytes);
    43. String[] result = storageClient.upload_file(bytes, suffix, null);
    44. System.out.println(JSON.toJSONString(result));
    45. //文件上传后,重新封装返回数据
    46. response.setCode(ResultCode.SUCCESS.getCode());
    47. response.setMsg(ResultCode.SUCCESS.getMsg());
    48. String url =fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port+"/" +result[0]+"/"+result[1];
    49. response.setData(url);
    50. } finally {
    51. //向用户响应上传成功的访问地址
    52. return response;
    53. }
    54. }
    55. }

     封装成Utils工具类

    BaseFastDFSUtil.java
    1. /*
    2. * FastDFS工具类
    3. * */
    4. public class BaseFastDFSUtil {
    5. /*
    6. * 配置文件
    7. * */
    8. private final static String propFilePath="fastdfs-client.properties";
    9. static {
    10. //加载fastdfs-client.properties配置文件
    11. try {
    12. ClientGlobal.initByProperties(propFilePath);
    13. } catch (IOException | MyException e) {
    14. e.printStackTrace();
    15. }
    16. }
    17. /*
    18. *文件上传到fastdfs
    19. *fdfs_storage_proxy_url storage web服务地址
    20. * inputStream 上传文件的自己输入流
    21. * file_etx_name 上传文件的后缀名
    22. * 上传成功后的web地址
    23. * */
    24. public static String upload(String fdfs_storage_proxy_url, InputStream inputStream,String file_ext_name) throws Exception {
    25. //获取tracker和storage客户端对象
    26. TrackerClient client = new TrackerClient();
    27. //获取tracker地址
    28. TrackerServer trackerServer = client.getTrackerServer();
    29. StorageServer storageServer=null;
    30. //获取storage地址
    31. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    32. int length = inputStream.available();
    33. byte[] bytes = new byte[length];
    34. //文件上传成功后重新封装返回数据
    35. inputStream.read(bytes);
    36. String[] result = storageClient.upload_file(bytes, file_ext_name, null);
    37. System.out.println(JSON.toJSONString(result));
    38. //断开连接
    39. storageClient.close();
    40. return fdfs_storage_proxy_url+"/" +result[0]+"/"+result[1];
    41. }
    42. }
    FdfsController.java
    1. @RestController
    2. @RequestMapping("/fdfs")
    3. public class FdfsController {
    4. @Value("${fdfs_storage_proxy.protocol}")
    5. private String fdfs_storage_proxy_protocol;
    6. @Value("${fdfs_storage_proxy.domain}")
    7. private String fdfs_storage_proxy_domain;
    8. @Value("${fdfs_storage_proxy.port}")
    9. private String fdfs_storage_proxy_port;
    10. @GetMapping("/proxy")
    11. public String proxy(){
    12. return fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port;
    13. }
    14. @GetMapping(value = "/hello")
    15. public String hello(){
    16. return "桃李不言下";
    17. }
    18. @RequestMapping("/upload1")
    19. public R<String>update01(@RequestParam("header")MultipartFile multipartFile){
    20. //封装返回数据 默认为上传失败
    21. R<String> response = new R<>(ResultCode.UPLOAD_FAILED.getCode(), ResultCode.UPLOAD_FAILED.getMsg(), null);
    22. //获取原文件的名字
    23. String originalFilename = multipartFile.getOriginalFilename();
    24. //获取源文件后缀名
    25. String suffix = FilenameUtils.getExtension(originalFilename);
    26. //文件上传
    27. try {
    28. //加载fastdfs-client.properties配置文件
    29. ClientGlobal.initByProperties("fastdfs-client.properties");
    30. //获取tracker和storage客户端对象
    31. TrackerClient client = new TrackerClient();
    32. //获取tracker地址
    33. TrackerServer trackerServer = client.getTrackerServer();
    34. StorageServer storageServer=null;
    35. //获取storage地址
    36. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    37. //文件上传字节数组
    38. InputStream inputStream = multipartFile.getInputStream();
    39. int length = inputStream.available();
    40. byte[] bytes = new byte[length];
    41. //文件上传成功后重新封装返回数据
    42. inputStream.read(bytes);
    43. String[] result = storageClient.upload_file(bytes, suffix, null);
    44. System.out.println(JSON.toJSONString(result));
    45. //文件上传后,重新封装返回数据
    46. response.setCode(ResultCode.SUCCESS.getCode());
    47. response.setMsg(ResultCode.SUCCESS.getMsg());
    48. //断开连接
    49. storageClient.close();
    50. String url =fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port+"/" +result[0]+"/"+result[1];
    51. response.setData(url);
    52. } finally {
    53. //向用户响应上传成功的访问地址
    54. return response;
    55. }
    56. }
    57. @RequestMapping("/upload2")
    58. public R<String>update02(@RequestParam("header")MultipartFile multipartFile){
    59. //封装返回数据 默认为上传失败
    60. R<String> response = new R<>(ResultCode.UPLOAD_FAILED.getCode(), ResultCode.UPLOAD_FAILED.getMsg(), null);
    61. //获取原文件的名字
    62. String originalFilename = multipartFile.getOriginalFilename();
    63. //获取源文件后缀名
    64. String suffix = FilenameUtils.getExtension(originalFilename);
    65. //文件上传
    66. try {
    67. String proxy=fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port;
    68. String url = BaseFastDFSUtil.upload(proxy, multipartFile.getInputStream(), suffix);
    69. //文件上传后,重新封装返回数据
    70. response.setCode(ResultCode.SUCCESS.getCode());
    71. response.setMsg(ResultCode.SUCCESS.getMsg());
    72. response.setData(url);
    73. } finally {
    74. //向用户响应上传成功的访问地址
    75. return response;
    76. }
    77. }
    78. }

    下载图片

    utils层

    1. /**
    2. * 文件下载
    3. *
    4. * @param groupName 组/卷名,默认值:group1
    5. * @param remoteFileName 文件名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg"
    6. * @return 文件的字节输入流
    7. */
    8. public static InputStream downloadFile(String groupName, String remoteFileName) {
    9. try {
    10. // 链接FastDFS服务器,创建tracker和Stroage
    11. TrackerClient trackerClient = new TrackerClient();
    12. TrackerServer trackerServer = trackerClient.getTrackerServer();
    13. StorageServer storageServer=trackerClient.getStoreStorage(trackerServer);
    14. //定义Stroage客户端对象,需要使用这个对象来完成具体的文件上传,下载和删除操作
    15. StorageClient storageClient = new StorageClient(trackerServer,storageServer);
    16. // 根据组名和文件名通过 Storage 客户端获取文件的字节数组
    17. byte[] bytes = storageClient.download_file(groupName == null ? "group1" : groupName, remoteFileName);
    18. // 返回字节流对象
    19. InputStream inputStream = new ByteArrayInputStream(bytes);
    20. return inputStream;
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. } catch (MyException e) {
    24. e.printStackTrace();
    25. }
    26. return null;
    27. }
    Controller层
    1. /**
    2. * 文件下载
    3. */
    4. @PostMapping("/downloadFile")
    5. public R downloadFile(@RequestParam("groupName")String groupName,@RequestParam("remoteFileName") String remoteFileName) throws Exception {
    6. //封装返回数据 默认为上传失败
    7. R response = new R<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), "下载成功");
    8. //调用下载接口
    9. InputStream is = BaseFastDFSUtil
    10. .downloadFile(groupName, remoteFileName);
    11. File file = new File("D:/" + remoteFileName);
    12. //判断目录是否存在如果不存在则存在
    13. //getParent()——得到路径的父级及以上的目录,String类型。
    14. //getParentFile()——得到路径的父级及以上的目录实例化的File对象。
    15. //createNewFile()创建文件
    16. //mkdir()——仅创建一层目录,返回true或false.
    17. //mkdirs()——创建一层或多层目录,返回true或false.
    18. if (!file.exists()){
    19. boolean dr = file.getParentFile().mkdirs(); //创建目录
    20. }
    21. OutputStream os = new FileOutputStream(new File("D:/" + remoteFileName));
    22. int index = 0 ;
    23. while((index = is.read())!=-1){
    24. os.write(index);
    25. }
    26. os.flush();
    27. os.close();
    28. is.close();
    29. return response;
    30. }

    删除图片

    Utils层

    1. /**
    2. * 文件删除
    3. *
    4. * @param groupName 组/卷名,默认值:group1
    5. * @param remoteFileName 文件名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg"
    6. * @return 0为成功,非0为失败
    7. */
    8. public static int deleteFile(String groupName, String remoteFileName) {
    9. int result = -1;
    10. try {
    11. // 链接FastDFS服务器,创建tracker和Stroage
    12. TrackerClient trackerClient = new TrackerClient();
    13. TrackerServer trackerServer = trackerClient.getTrackerServer();
    14. StorageServer storageServer=trackerClient.getStoreStorage(trackerServer);
    15. //定义Stroage客户端对象,需要使用这个对象来完成具体的文件上传,下载和删除操作
    16. StorageClient storageClient = new StorageClient(trackerServer,storageServer);
    17. // 根据组名和文件名通过 Storage 客户端删除文件
    18. result = storageClient.delete_file(groupName == null ? "group1" : groupName, remoteFileName);
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. } catch (MyException e) {
    22. e.printStackTrace();
    23. }
    24. return result;
    25. }

    Controller层

    1. // 文件删除
    2. @PostMapping("/testDeleteFile")
    3. public void testDeleteFile(@RequestParam("groupName")String groupName,@RequestParam("remoteFileName") String remoteFileName) {
    4. int result = BaseFastDFSUtil.deleteFile(groupName, remoteFileName);
    5. System.out.println("result = " + result);
    6. }

    修改文件

    Utils工具类层

    1. /**
    2. * 修改一个已经存在的文件
    3. *
    4. * @param oldGroupName 旧组名
    5. * @param oldFileName 旧文件名
    6. * @param file 新文件
    7. * @param fileName 新文件名
    8. * @return
    9. */
    10. public static String modifyFile(String oldGroupName, String oldFileName, MultipartFile file) throws Exception {
    11. // 先上传
    12. String stringR = update01(file);
    13. // 再删除
    14. int delResult = deleteFile(oldGroupName, oldFileName);
    15. if (delResult != 0) {
    16. return null;
    17. }
    18. return stringR;
    19. }
    20. /*
    21. *文件上传到fastdfs
    22. *fdfs_storage_proxy_url storage web服务地址
    23. * inputStream 上传文件的自己输入流
    24. * file_etx_name 上传文件的后缀名
    25. * 上传成功后的web地址
    26. * */
    27. public static String update01(MultipartFile multipartFile) throws Exception {
    28. //获取原文件的名字
    29. String originalFilename = multipartFile.getOriginalFilename();
    30. //获取源文件后缀名
    31. String suffix = FilenameUtils.getExtension(originalFilename);
    32. //文件上传
    33. //加载fastdfs-client.properties配置文件
    34. ClientGlobal.initByProperties("fastdfs-client.properties");
    35. //获取tracker和storage客户端对象
    36. TrackerClient client = new TrackerClient();
    37. //获取tracker地址
    38. TrackerServer trackerServer = client.getTrackerServer();
    39. StorageServer storageServer = null;
    40. //获取storage地址
    41. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    42. //文件上传字节数组
    43. InputStream inputStream = multipartFile.getInputStream();
    44. int length = inputStream.available();
    45. byte[] bytes = new byte[length];
    46. //文件上传成功后重新封装返回数据
    47. inputStream.read(bytes);
    48. String[] result = storageClient.upload_file(bytes, suffix, null);
    49. System.out.println(JSON.toJSONString(result));
    50. String url = "http://" + "39.97.100.141" + ":" + "8888" + "/" + result[0] + "/" + result[1];
    51. return url;
    52. }
    53. /*
    54. *文件上传到fastdfs
    55. *fdfs_storage_proxy_url storage web服务地址
    56. * inputStream 上传文件的自己输入流
    57. * file_etx_name 上传文件的后缀名
    58. * 上传成功后的web地址
    59. * */
    60. public static String upload(String fdfs_storage_proxy_url, InputStream inputStream, String file_ext_name) throws Exception {
    61. //获取tracker和storage客户端对象
    62. TrackerClient client = new TrackerClient();
    63. //获取tracker地址
    64. TrackerServer trackerServer = client.getTrackerServer();
    65. StorageServer storageServer=null;
    66. //获取storage地址
    67. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    68. int length = inputStream.available();
    69. byte[] bytes = new byte[length];
    70. //文件上传成功后重新封装返回数据
    71. inputStream.read(bytes);
    72. String[] result = storageClient.upload_file(bytes, file_ext_name, null);
    73. System.out.println(JSON.toJSONString(result));
    74. //断开连接
    75. storageClient.close();
    76. return fdfs_storage_proxy_url+"/" +result[0]+"/"+result[1];
    77. }

    Controller层

    1. // 文件替换
    2. @PostMapping("/testModifyFile")
    3. public String testModifyFile(@RequestParam("groupName")String groupName,@RequestParam("remoteFileName") String remoteFileName,@RequestParam("header")MultipartFile file) throws Exception {
    4. //封装返回数据 默认为上传失败
    5. String fileids = BaseFastDFSUtil.modifyFile(groupName, remoteFileName,file);
    6. return fileids;
    7. }

    FastDFS校验文件类型

    配置yaml

    1. upload:
    2. base-url: http://116.62.44.5/
    3. allow-types:
    4. - image/jpeg
    5. - image/png
    6. - image/bmp
    7. - image/gif

    创建配置类UploadProperties

    1. package com.coydone.config;
    2. import org.springframework.boot.context.properties.ConfigurationProperties;
    3. import java.util.List;
    4. @ConfigurationProperties(prefix = "upload")
    5. public class UploadProperties {
    6. private String baseUrl;
    7. private List<String> allowTypes;
    8. public String getBaseUrl() {
    9. return baseUrl;
    10. }
    11. public void setBaseUrl(String baseUrl) {
    12. this.baseUrl = baseUrl;
    13. }
    14. public List<String> getAllowTypes() {
    15. return allowTypes;
    16. }
    17. public void setAllowTypes(List<String> allowTypes) {
    18. this.allowTypes = allowTypes;
    19. }
    20. }

    在Controller使用

    1. @RestController
    2. @Component
    3. @EnableConfigurationProperties(UploadProperties.class)
    4. @RequestMapping("/fdfs")
    5. public class FdfsController {
    6. @Autowired
    7. private UploadProperties prop;
    8. @RequestMapping("/upload1")
    9. public R update01(@RequestParam("header") MultipartFile multipartFile){
    10. //封装返回数据 默认为上传失败
    11. R response = new R<>(ResultCode.UPLOAD_FAILED.getCode(), ResultCode.UPLOAD_FAILED.getMsg(), null);
    12. //获取原文件的名字
    13. String originalFilename = multipartFile.getOriginalFilename();
    14. //获取源文件后缀名
    15. String suffix = FilenameUtils.getExtension(originalFilename);
    16. System.out.println("获取源文件后缀名"+suffix);
    17. // 1、校验文件类型
    18. String contentType = multipartFile.getContentType();
    19. if (!prop.getAllowTypes().contains(contentType)) {
    20. throw new RuntimeException("文件类型不支持");
    21. }
    22. // 2、校验文件内容
    23. try {
    24. BufferedImage image = ImageIO.read(multipartFile.getInputStream());
    25. if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
    26. throw new RuntimeException("上传文件有问题");
    27. }
    28. } catch (IOException e) {
    29. throw new RuntimeException("校验文件内容失败"+e.getMessage());
    30. }
    31. try {
    32. //加载fastdfs-client.properties配置文件
    33. ClientGlobal.initByProperties("fastdfs-client.properties");
    34. //获取tracker和storage客户端对象
    35. TrackerClient client = new TrackerClient();
    36. //获取tracker地址
    37. TrackerServer trackerServer = client.getTrackerServer();
    38. StorageServer storageServer=null;
    39. //获取storage地址
    40. StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    41. //文件上传字节数组
    42. InputStream inputStream = multipartFile.getInputStream();
    43. int length = inputStream.available();
    44. byte[] bytes = new byte[length];
    45. //文件上传成功后重新封装返回数据
    46. inputStream.read(bytes);
    47. String[] result = storageClient.upload_file(bytes, suffix, null);
    48. System.out.println(JSON.toJSONString(result));
    49. //文件上传后,重新封装返回数据
    50. response.setCode(ResultCode.SUCCESS.getCode());
    51. response.setMsg(ResultCode.SUCCESS.getMsg());
    52. String url =fdfs_storage_proxy_protocol+fdfs_storage_proxy_domain+":"+fdfs_storage_proxy_port+"/" +result[0]+"/"+result[1];
    53. response.setData(url);
    54. } finally {
    55. //向用户响应上传成功的访问地址
    56. return response;
    57. }
    58. }
    59. }

  • 相关阅读:
    CorelDRAW2022标准专业订阅版下载及功能介绍
    【Ubuntu上使用git链接私人仓库】
    shell编程基础
    SQL SERVER EXEC 、SP_EXECUTESQL
    AIGC程序员效能提升之道
    modbusRTU【codesys】
    MySQL报错:json_contains: “The document is empty.“ at position 0.
    Redis缓存
    自制操作系统日志——第九天
    简易实现通讯录3.0 (实现文件操作)
  • 原文地址:https://blog.csdn.net/weixin_53998054/article/details/126104560