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(xxx),pcip.api.jhStreetName(xxx)");
        }
        if (jhStreetName.equals(streetName)) {
            if (ObjectUtil.isEmpty(jhFileServer)) {
                throw new BusinessException("请联系管理员,配置XXX文件服务器地址: pcip.api.jhFilesApi");
            }
            xcFileUrl = jhFileServer + xcFilePath;
        } else if (blStreetName.equals(streetName)) {
            if (ObjectUtil.isEmpty(blFileServer)) {
                throw new BusinessException("请联系管理员,配置XXX文件服务器地址: 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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的URLConnection类来实现文件上传。下面是一个简单的示例代码: ``` import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) { String serverUrl = "http://example.com/upload.php"; // 服务器上传接口地址 String filePath = "path/to/image.jpg"; // 本地文件路径 String serverPath = "/var/www/html/uploads/"; // 服务器目标路径 try { // 创建连接 URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------123821742118716"); connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\""); // 读取文件并写入请求体 FileInputStream fileInputStream = new FileInputStream(new File(filePath)); OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 结束请求体 outputStream.flush(); outputStream.write("\r\n".getBytes()); outputStream.write("-----------------------------123821742118716--\r\n".getBytes()); // 发送请求并获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败,错误代码:" + responseCode); } // 关闭连接 fileInputStream.close(); outputStream.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们创建一个HTTP连接对象,并设置请求头部信息。然后,我们读取本地文件,将其写入请求体,再发送请求并获取响应。最后,我们关闭连接。请注意,这段代码只是一个示例,你需要根据自己的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值