Ambry(1)—— 分布式对象存储数据库Ambry文件的上传下载功能逻辑代码

上传:

/**
     * 分布式对象存储系统Ambry文件上传接口
     *
     * @param file    请求文件
     * @param request r
     * @return T
     */
    @PostMapping(value = "/uploadfile")
    public String UploadFile(@RequestBody MultipartFile file, HttpServletRequest request) {
        LOGGER.info("开始进行Ambry分布式对象存储文件上传...");
        return (ambryService.uploadFile(file, request));
    }




/**
     * 服务上传的对象
     */
    private static final String SERVICEID = "CUrlUpload";
    /**
     * 指定对象的拥有者
     */
    private static final String OWNER = "root";
    /**
     * 上传对象的描述
     */
    private static final String DESCRIPTION = "Demonstration File";

    /**
     * 分布式对象存储Ambry上传文件
     *
     * @param multipartFile 源文件
     * @param request       请求
     * @return str
     */
    public static String uploadFile(MultipartFile multipartFile, AmbryConfigProperties ambryConfigProperties,
                                    HttpServletRequest request) {
        HttpURLConnection connection = null;
        OutputStream os = null;
        DataInputStream is = null;
        InputStream inputStream = null;
        int count = 0;
        //获取项目根目录
        String tmpFilePath = request.getSession().getServletContext().getRealPath("/");
        //自定义压缩文件名称
        String zipName = DateUtil.currentDate(DateUtil.YMD).concat("_").concat(String.valueOf(System.currentTimeMillis()));
        while (count <= 3) {
            try {
                String fileName = multipartFile.getOriginalFilename();
                LOGGER.info("上传的文件名:" + fileName);
                String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
                LOGGER.info("上传的后缀名为:" + suffixName);
                // 自定义的文件名称
                String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                String path = tmpFilePath + trueFileName;
                LOGGER.info("文件上传临时路径:" + path);
                File file = new File(path);
                multipartFile.transferTo(file);
                if (!fileContentType(file).contains("image")) {
                    inputStream = new StreamGenerator(file, tmpFilePath, zipName).getInputStream();
                } else {
                    inputStream = new FileInputStream(file);
                }
                int length = inputStream.available();
                connection = (HttpURLConnection) new URL(ambryConfigProperties.getAmbryuploadurl()).openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/octet-stream");
                //设置是否从httpUrlConnection读入,默认情况下是true;
                connection.setDoOutput(true);
                //设置是否向httpUrlConnection输出,默认为false
                connection.setDoInput(true);
                connection.setRequestProperty("x-ambry-blob-size", String.valueOf(length));
                connection.addRequestProperty("x-ambry-service-id", SERVICEID);
                connection.addRequestProperty("x-ambry-owner-id", OWNER);
                connection.addRequestProperty("x-ambry-content-type", suffixName);
                connection.addRequestProperty("x-ambry-um-description", DESCRIPTION);
                connection.connect();
                LOGGER.info("成功连接Ambry分布式对象存储系统...");
                os = new BufferedOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[4096];
                int bytes_read;
                //只要可以读取到数据,就输出写到buffer中
                while ((bytes_read = inputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytes_read);
                }
                //数据读取完关闭inputStream
                os.close();
                inputStream.close();
                String location = connection.getHeaderField("Location");
                LOGGER.info("返回信息:" + location);
                //删除本地缓存文件
                file.delete();
                return (ambryConfigProperties.getAmbryuploadurl().concat(location));
            } catch (Exception e) {
                count++;
                try {
                    TimeUnit.SECONDS.sleep(1L);
                } catch (InterruptedException e1) {
                    LOGGER.warn(ExceptionUtils.getStackTrace(e1));
                }
                LOGGER.warn(ExceptionUtils.getStackTrace(e));
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                } catch (IOException e) {
                    LOGGER.warn(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        return null;
    }

    /**
     * 获取文件类型
     *
     * @param file 文件
     * @return 文件类型
     */
    private static String fileContentType(File file) {
        try {
            String filename = file.getName();
            //根据文件获取文件类型
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            //contentType非空采用filename匹配默认的图片类型
            if (!"".equals(contentType)) {
                if (filename.endsWith(".png")) {
                    contentType = "image/png";
                } else if (filename.endsWith(".jpg")
                        || filename.endsWith(".jpeg")
                        || filename.endsWith(".jpe")) {
                    contentType = "image/jpeg";
                } else if (filename.endsWith(".gif")) {
                    contentType = "image/gif";
                } else if (filename.endsWith(".ico")) {
                    contentType = "image/image/x-icon";
                }
            }
            if (CommonUtil.isEmpty(contentType)) {
                contentType = "application/octet-stream";
            }
            return contentType;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获取文件类型错误" + e.getMessage());
            return null;
        }
    }

下载:

 /**
     * 分布式对象存储系统Ambry文件下载接口
     *
     * @param userid   用户id
     * @param trackid  轨迹id
     * @param request  req
     * @param response res
     */
    @GetMapping(value = "/downfile/{userid}/{trackid}")
    public String downFile(@PathVariable("userid") Long userid, @PathVariable("trackid") String trackid, HttpServletRequest request,
                         HttpServletResponse response) {
        LOGGER.info("开始进行Ambry分布式对象存储文件下载...");
        return ambryService.downFile(userid, trackid, request, response);
    }


 /**
     * 执行文件下载
     *
     * @param userid   用户ID
     * @param trackid  轨迹id
     * @param request  req
     * @param response res
     *                 <p>
     *                 例:
     *                 压缩文件:/AAEAAQAAAAAAAAAAAAAAJGEwMDhkMDVlLTEzMzUtNDFkMy05ODE3LTljZjcwNzZjNjYzNA
     *                 非压缩文件:/AAEAAQAAAAAAAAAAAAAAJDJlMWFiODYwLWZkZWEtNDgzNi1iN2NmLTdmY2YzZDUzNGUxOA
     */
    @Override
    public String downFile(Long userid, String trackid,
                           HttpServletRequest request, HttpServletResponse response) {
        if (CommonUtil.isEmpty(userid)) {
            LOGGER.warn("用户ID不能为空!");
        }
        if (CommonUtil.isEmpty(trackid)) {
            LOGGER.warn("运动轨迹ID不能为空!");
        }
        //获取分布式对象存储数据库Ambry的运动轨迹路径
        String downUrl = ambryConfigProperties.getAmbryuploadurl().concat("/AAEAAQAAAAAAAAAAAAAAJGEwMDhkMDVlLTEzMzUtNDFkMy05ODE3LTljZjcwNzZjNjYzNA");
        LOGGER.info("分布式对象存储源文件下载地址:" + downUrl);
        /**
         * 本调用完成以下三步骤
         * 1、执行分布式对象存储数据库Ambry压缩文件下载,并将下载后的压缩文件保存本地,返回下载地址
         * 2、根据压缩文件的下载地址,开始执行压缩文件的解压操作,将解压后的文件保存本地,返回解压后的文件
         * 3、前端请求,开始执行本地解压后的文件进行网络下载
         */
        AmbryUploadUtil.downLoadFile(request, response,
                AmbryUploadUtil.unZipFiles(
                        AmbryUploadUtil.downAmbryZipFile(downUrl, request), request));
        return "success";
    }


/**
     * 执行分布式对象存储数据库Ambry压缩文件下载,并将下载后的压缩文件保存本地,返回压缩文件下载地址
     *
     * @param downUrl Ambry压缩文件下载地址
     * @param request req
     * @return File
     */
    public static File downAmbryZipFile(String downUrl, HttpServletRequest request) {
        HttpURLConnection connection = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            connection = (HttpURLConnection) new URL(downUrl).openConnection();
            connection.connect();
            bis = new BufferedInputStream(connection.getInputStream());
            String tmpFilePath = request.getSession().getServletContext().getRealPath("/");
            String zipName = DateUtil.currentDate(DateUtil.YMD).concat("_").concat(String.valueOf(System.currentTimeMillis())).concat(".zip");
            //创建文件目录
            File tmpFile = new File(tmpFilePath);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            //创建文件
            File localFile = new File(tmpFilePath, zipName);
            bos = new BufferedOutputStream(new FileOutputStream(localFile));
            int len = -1;
            byte[] b = new byte[2048];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            LOGGER.info("分布式本地压缩文件ZIP下载地址:" + localFile);
            return localFile;
        } catch (Exception e) {
            CommonUtil.getExceptionStackTrace(e);
            return null;
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
                if (null != bis) {
                    bis.close();
                }
                if (null != connection) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据压缩文件的下载地址,开始执行压缩文件的解压操作,将解压后的文件保存本地,返回解压后的文件
     *
     * @param localFile 本地压缩文件地址
     * @param request   req
     * @return str
     */
    public static String unZipFiles(File localFile, HttpServletRequest request) {
        InputStream in = null;
        OutputStream out = null;
        ZipFile zf = null;
        try {
            String descDir = request.getSession().getServletContext().getRealPath("/");
            //创建目录
            File descFileDir = new File(descDir);
            if (!descFileDir.exists()) {
                descFileDir.mkdirs();
            }
            zf = new ZipFile(localFile);
            for (Enumeration entries = zf.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                in = zf.getInputStream(entry);
                File descFile = new File(descDir, zipEntryName);
                out = new FileOutputStream(descFile);
                byte[] buf1 = new byte[2048];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                LOGGER.info("本地压缩文件解压缩完成,本地解压后文件地址:" + descFile.getPath());
                return descFile.getPath();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
                if (null != zf) {
                    zf.close();
                }
                if (null != localFile) {
                    localFile.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 前端请求,开始执行本地解压后的文件进行网络下载
     *
     * @param request  req
     * @param response res
     * @throws Exception
     */
    public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String path) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File file = new File(path);
        try {
            request.setCharacterEncoding("UTF-8");
            long fileLength = file.length();
            String cname = path.substring(path.lastIndexOf("\\") + 1);
            response.setContentType("application/octet-stream");
            //解决火狐浏览器下载文件中文名乱码问题
            String agent = (String) request.getHeader("USER-AGENT");
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                cname = "=?UTF-8?B?" + (new String(Base64.encodeBase64(cname.getBytes("UTF-8")))) + "?=";
                response.setHeader("Content-disposition", "attachment; filename="
                        + cname);
            }
            //解决safari浏览器下载文件中文乱码问题
            else if (agent != null && agent.toLowerCase().indexOf("safari") > 0) {
                response.setHeader("Content-disposition", "attachment; filename="
                        + (new String(cname.getBytes("UTF-8"), "ISO-8859-1")));
            } else {
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode(cname, "UTF-8"));
            }
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(path));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int temp;
            while (-1 != (temp = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, temp);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
                if (null != bis) {
                    bis.close();
                }
                if (null != file) {
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

转载于:https://www.cnblogs.com/xushuyi/articles/7126988.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值