springBoot整合fastdfs 上传下载

  1. 目录结构
    2.
    pom
  <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.7</version>
        </dependency>

yml

server:
  port: 8081


fdfs:
  so-timeout: 2500       # 读取时间
  connect-timeout: 600   # 连接超时时间
  thumb-image:           # 缩略图
    width: 100
    height: 100
  tracker-list:          # tracker服务配置地址列表
    - 192.168.161.131:22122

upload:
  base-url: http://192.168.161.131/
  allow-types:
    - image/jpeg
    - image/png
    - image/bmp
    - image/gif
    - application/msword

entity

@ConfigurationProperties(prefix = "upload")
@Data
@Component
public class UploadProperties {

    private String baseUrl;

    private List<String> allowTypes;
}

util

@Component
@Slf4j
public class UploadUtil {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private UploadProperties prop;


    public String uploadImage(MultipartFile file) {
        // 1、校验文件类型
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件类型不支持");
        }
        // 2、校验文件内容
        try {
            if (file == null ) {
                throw new RuntimeException("上传文件有问题");
            }
        } catch (Exception 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 prop.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败!....{}", e);
            throw new RuntimeException("【文件上传】上传文件失败!" + e.getMessage());
        }
    }

    /**
     * 文件下载
     *
     * @param fileId   文件id
     * @param response
     * @param downName 文件下载后保存的名字
     * @return
     * @throws IOException
     */
    public void downloadFile(String fileId, HttpServletResponse response, String downName) throws IOException {
        //获取group
        String group = fileId.substring(0, fileId.indexOf("/"));
        //获取路径
        String path = fileId.substring(fileId.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(downName, "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();
            }
        }
    }


}

controller

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadUtil uploadUtil;

    @RequestMapping("doUpload")
    public Map<String, Object> doUpload(MultipartFile mf) {
        //文件名和返回的url保存到数据库 下载的时候通过url找到对应的文件名
        System.out.println(mf.getOriginalFilename());
        Map<String, Object> map = new HashMap<>();
        String url = uploadUtil.uploadImage(mf);
        map.put("url", url);
        return map;
    }

    @RequestMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
        fileUrl = "group1/M00/00/00/wKihg1_Our6ANj1rAADoABeizWQ229.doc";
        uploadUtil.downloadFile(fileUrl,response,"11.doc");
        // 这里只是为了整合fastdfs,所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式

    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


    <h1>文件上传</h1>
    <hr>
    <form action="/upload/doUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="mf">
        <input type="submit" value="上传">
    </form>

</body>
</html>

码云地址:https://gitee.com/zhu_can_admin/elaticsearch.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值