温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java怎么实现整合文件上传到FastDFS

发布时间:2022-02-28 09:18:56 来源:亿速云 阅读:185 作者:小新 栏目:开发技术

这篇文章主要介绍Java怎么实现整合文件上传到FastDFS,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

    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”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI