栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java图片上传到指定服务器,下载到指定目录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java图片上传到指定服务器,下载到指定目录

// 图片下载后上传至指定服务器
    public String uploadXCFile(String imageUrl, String streetName) throws IOException {
        System.out.println("--------------进入上传文件到巡查系统----------------------");
        String xcFilePath = "/fmp/uploadFile";
        String xcFileUrl = "";
        String downFileUrl = fileServer + "/files/" + imageUrl;
        if(ObjectUtil.isEmpty(fileServer)) {
            throw new BusinessException("请联系管理员,配置文件服务地址:pcip.api.filesApi");
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            System.out.println("--------------把文件转成流start----------------------");
            HttpUtil.download(downFileUrl, bos, true);
            System.out.println("--------------把文件转成流end----------------------");
        } catch (Exception e) {
            throw new BusinessException("该文件不存在,请检查", e);
        }
        if (ObjectUtil.isEmpty(jhStreetName) ||  ObjectUtil.isEmpty(blStreetName)) {
            throw new BusinessException("请联系管理员,配置添加配置名称: pcip.api.blStreetName(宝龙),pcip.api.jhStreetName(吉华)");
        }
        if (jhStreetName.equals(streetName)) {
            if (ObjectUtil.isEmpty(jhFileServer)) {
                throw new BusinessException("请联系管理员,配置吉华文件服务器地址: pcip.api.jhFilesApi");
            }
            xcFileUrl = jhFileServer + xcFilePath;
        } else if (blStreetName.equals(streetName)) {
            if (ObjectUtil.isEmpty(blFileServer)) {
                throw new BusinessException("请联系管理员,配置宝龙文件服务器地址: pcip.api.blFilesApi");
            }
            xcFileUrl = blFileServer + xcFilePath;
        } else {
            return null;
        }
        System.out.println("--------------开始向巡查系统上传文件start----------------------");
        String path = HttpUtil.createPost(xcFileUrl)
                .contentType("multipart/form-data")
                .form("file", new BytesResource(bos.toByteArray(),imageUrl))
//                .header("refreshToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ3ZWIiLCJpc3MiOiJ0b3BldmVyeSIsInBfbG9naW5fbmFtZSI6ImFkbWluIiwiZXhwIjoxNjM0MzczNzM4LCJpYXQiOjE2MzM3Njg5MzgsImp0aSI6IkI2QzE0OTIwLTVBQzctNEYwMS1BNTZELTdCQUJFN0U5RTA3NSJ9.VESuchKRY0N_P4MaHOhae0ivU1KKOrI1YV7d3YRi0wY")
//                .header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ3ZWIiLCJpc3MiOiJ0b3BldmVyeSIsInBfbG9naW5fbmFtZSI6ImFkbWluIiwiZXhwIjoxNjM0MTc2Nzk4LCJpYXQiOjE2MzQwOTAzOTgsImp0aSI6IkRERTZFNDNFLUI0MzQtNDUzOS05RDZDLTM3N0JCNzA3M0Q4MiJ9.LYIaHO5RUSKv5r2_OERAw34qLt5TZvvczH_xrHE6GZ0")
                .execute()
                .body();
        Result result=JSONUtil.toBean(path, Result.class);
        System.out.println("--------------向巡查系统上传文件结束end----------------------");
        System.out.println("path:" + path);
        if (!result.isSuccess()) {
            throw new BusinessException("图片上传巡查系统失败,请联系管理员检查!");
        }
        HashMap map = (HashMap) result.getData();
        String xcfileId = map.get("fileId").toString();
//        // 先下载文件
//        String tempPath = this.downFile(downFileUrl);
//        File file = new File(tempPath);
//        try {
//            FileInputStream fileInputStream = new FileInputStream(file);
//            MultipartFile multipartFile = new CommonsMultipartFile(file);
//            xcFileUrl = this.upload(multipartFile);
//            fileInputStream.close();
//            System.out.println(xcFileUrl);
//        } catch (FileNotFoundException e) {
//            throw new BusinessException("文件未找到");
//        } catch (IOException e) {
//            throw new BusinessException("文件流异常");
//        } finally {
//        }
        return xcfileId;
    }

public String downFile(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 文件保存临时目录
        String folder = "tempFiles";
        File dir = new File(folder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = getFileName(url.getPath());
        File localFile = new File(dir, fileName);
        try (
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile));
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream())
        ) {
            int len = 1024;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            conn.disconnect();
        } catch (IOException e) {
            throw new BusinessException("### 下载文件" + localFile.getCanonicalPath() + "发生异常。" + e);
        }

        System.out.println("### 下载文件:"+fileUrl+"到本地:"+localFile.getCanonicalPath()+"成功。");
        System.out.println("下载临时目录:" + localFile.getCanonicalPath());
        return localFile.getCanonicalPath();
    }

    private static String getFileName(String remoteUrl) {
        String decode = null;
        try {
            decode = URLDecoder.decode(remoteUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(decode);
        return file.getName();
    }

    public String upload(MultipartFile multipartFile) {
        String path = null;
        String fileServer = "https://xxx.xxx.xx.xx/fmp/uploadFile";
        if (ObjectUtil.isEmpty(fileServer)) {
            throw new BusinessException("未获取到文件服务器地址的配置[topevery.file-intranet-server]");
        }
        System.out.println("multipartFile.getOriginalFilename():" +multipartFile.getOriginalFilename());
        System.out.println(multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().lastIndexOf(".")));
        try {
            path = HttpUtil.createPost(fileServer)
//                    .contentType("multipart/form-data")
//                    .form("Content-Disposition", "multipart/form-data")
//                    .form("name", "file")
//                    .form("filename", multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().lastIndexOf(".") - 1))
//                    .form("Content-Type", "image/png")
//                    .form("file", multipartFile)
                    .contentType("multipart/form-data")
                    .form("file", multipartFile)
                    .header("refreshToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ3ZWIiLCJpc3MiOiJ0b3BldmVyeSIsInBfbG9naW5fbmFtZSI6ImFkbWluIiwiZXhwIjoxNjM0MzczNzM4LCJpYXQiOjE2MzM3Njg5MzgsImp0aSI6IkI2QzE0OTIwLTVBQzctNEYwMS1BNTZELTdCQUJFN0U5RTA3NSJ9.VESuchKRY0N_P4MaHOhae0ivU1KKOrI1YV7d3YRi0wY")
                    .header("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ3ZWIiLCJpc3MiOiJ0b3BldmVyeSIsInBfbG9naW5fbmFtZSI6ImFkbWluIiwiZXhwIjoxNjM0MTc2Nzk4LCJpYXQiOjE2MzQwOTAzOTgsImp0aSI6IkRERTZFNDNFLUI0MzQtNDUzOS05RDZDLTM3N0JCNzA3M0Q4MiJ9.LYIaHO5RUSKv5r2_OERAw34qLt5TZvvczH_xrHE6GZ0")
                    .execute()
                    .body();
        } catch (Exception e) {
            throw new BusinessException("文件上传失败:" + e);
        }
        return path;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号