码迷,mamicode.com
首页 > 编程语言 > 详细

FastDFS整合SpringBoot(五)

时间:2019-11-11 21:40:03      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:res   inpu   body   文件大小   name   actor   打开   fast   new   

  • pom.xml
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>



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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  • 配置类

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfig {

}

  • 包装类
@Component
public class FastDFSClientWrapper {
 
    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
 
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
 
    /**
     * 文件上传
     * 最后返回fastDFS中的文件名称;group1/M00/01/04/CgMKrVvS0geAQ0pzAACAAJxmBeM793.doc
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return fastDfs路径
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, null);
        logger.info(storePath.getGroup() + "==" + storePath.getPath() + "======" + storePath.getFullPath());
        return storePath.getFullPath();
    }
 
    /**
     * 下载文件
     *  返回文件字节流大小
     * @param fileUrl 文件URL
     * @return 文件字节
     * @throws IOException
     */
    public byte[] downloadFile(String group,String path) throws IOException {
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }
 
}
  • html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="upload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="file"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
  • application.yml
#fastdfs 配置
fdfs:
  so-timeout: 1500
  connect-timeout: 600
  thumb-image:
    width: 150
    height: 150
  tracker-list:
    - 192.168.180.104:22122
spring:
  thymeleaf:
    prefix: classpath:/templates/
  • web层
@RestController
public class FdfsController {
    
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;
    
    private final Logger logger = LoggerFactory.getLogger(FdfsController.class);
    
    @RequestMapping("file")
    public String file(){
        return "/fileUploade";
    }
    
    @PostMapping("/upload")
    public void upload(MultipartFile file) throws Exception {
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            logger.error("获取文件错误");
            e.printStackTrace();
        }
        //获取源文件名称
        String originalFileName = file.getOriginalFilename();
        //获取文件后缀--.doc
        String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String fileName = file.getName();
        //获取文件大小
        long fileSize = file.getSize();
        System.out.println(originalFileName + "==" + fileName + "==" + fileSize + "==" + extension + "==" + bytes.length);
         String string = fastDFSClientWrapper.uploadFile(bytes, fileSize, extension);
         //group1/M00/00/00/wKi0aF3I4dOAIhAXAAAG7e1-evI891.txt
         System.out.println(string);
    }
    
    @GetMapping("/downloadFile")
    public void downloadFile(String group,String path,String fileName,HttpServletResponse response) throws Exception {
        byte[] bytes = fastDFSClientWrapper.downloadFile(group, path);
        //设置相应类型application/octet-stream (注:applicatoin/octet-stream 为通用,一些其它的类型苹果浏览器下载内容可能为空)
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 写入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();

    }
       
    


}

技术图片

 

FastDFS整合SpringBoot(五)

标签:res   inpu   body   文件大小   name   actor   打开   fast   new   

原文地址:https://www.cnblogs.com/dalianpai/p/11838009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!