Java文件路径上传到指定url

上传图片/文件

废话不多说上代码

	public static void main(String[] args) {
        String fileUrl ="图片地址";
        String uploadUrl = "上传地址";
        // 原生http
        System.out.println(getUploadUrlByInputStream(fileUrl,uploadUrl));
        // restTemplate(依赖Jackson包,异常会提示如下错误)
        //nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/module/jaxb/JaxbAnnotationIntrospector
        System.out.println(getUploadUrlByByteArrayOutStream(fileUrl,uploadUrl));
    }

    public static String getUploadUrlByInputStream(String fileUrl, String hwObsUrl){
        InputStream stream = getInputStreamByImgUrl(fileUrl);
        if (stream == null) {
            log.info("InputStream is null:{}",fileUrl);
            return null;
        }
        long sysTime = System.currentTimeMillis();
        String fxHwUrl = null;
        try {
            String fileName = getFileName(fileUrl);
            String responseBody = postMultipartFile(hwObsUrl,fileName,stream);
            if (responseBody == null) {
                log.info("upload error api response is null:{}",fileUrl);
                return null;
            }
            JSONObject obj = JSONObject.parseObject(responseBody);
            fxHwUrl = obj.getJSONObject("data").getString("filePath");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("----------上传耗时:{}", System.currentTimeMillis() - sysTime);
        return fxHwUrl;
    }

    public static String getFileName(String fileUrl){
        String tempUrl = fileUrl;
        if(fileUrl.indexOf("?")>0){
            tempUrl = fileUrl.substring(0,fileUrl.indexOf("?"));
        }
        return tempUrl.substring(tempUrl.lastIndexOf("/")+1);
    }

    public static String postMultipartFile(String url, String fileName, InputStream stream) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);
            //加上此行代码解决返回中文乱码问题
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //文件流处理
            builder.addBinaryBody("file", stream, ContentType.MULTIPART_FORM_DATA, fileName);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity, "UTF-8");
        } catch (Exception e) {
            //打印日志
            e.printStackTrace();
            log.error("postMultipartFile error,url:{},ex:{}", url, e.getMessage());
        }
        return null;
    }


    public static InputStream getInputStreamByImgUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(2000);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return connection.getInputStream();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static String getUploadUrlByByteArrayOutStream(String fileUrl, String hwObsUrl){
        ByteArrayOutputStream stream = getByteArrayOutStreamByImgUrl(fileUrl);
        if (stream == null) {
            log.info("ByteArrayOutputStream is null:{}",fileUrl);
            return null;
        }
        long sysTime = System.currentTimeMillis();
        String fxHwUrl = null;
        try {
            String fileName = getFileName(fileUrl);
            HwObsUploadApiResponse responseBody = uploadToHwObs(hwObsUrl, stream, fileName);
            if (responseBody == null) {
                log.info("upload error api response is null:{}",fileUrl);
                return null;
            }

            fxHwUrl = responseBody.getFilePath();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("----------上传耗时:{}", System.currentTimeMillis() - sysTime);
        return fxHwUrl;
    }

    public static ByteArrayOutputStream getByteArrayOutStreamByImgUrl(String imageUrl) {
        try {
            InputStream inputStream = getInputStreamByImgUrl(imageUrl);
            if (null != inputStream) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                return byteArrayOutputStream;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值