java crate upload blob

文件上傳到crate的blob中,使用的是crate的rest方式,具體請參看crate的githubgit

代碼:github

public void uploadBlob(String filePath) {
//filepath指的是本地的文件絕對路徑
        try {
//            byte[] decoded = Base64.decodeBase64(File2byte(filePath));//若是是base64的須要解碼一下
            byte[] decoded = File2byte(filePath);
            String digest = DigestUtils.sha1Hex(decoded);
//            System.out.println(new String(decoded));
            HttpPut put = new HttpPut(blobUri(digest));
            put.setEntity(new ByteArrayEntity(decoded));
            CloseableHttpClient httpClient = HttpClients.createSystem();
            CloseableHttpResponse resp = httpClient.execute(put);
//            HTTPResp resp = this.client.put(blobUri(digest),decoded);
            System.out.println(resp.getStatusLine().getStatusCode());
            if (resp == null || resp.getStatusLine().getStatusCode() != 201) {
                System.out.println(resp);
                System.out.println(resp.getStatusLine().getStatusCode());
                System.out.println(resp.getEntity());
                System.out.println("執行插入失敗:" + resp.getStatusLine().getReasonPhrase());
            } else {
                System.out.println(resp.getStatusLine().getReasonPhrase());
            }
//            System.out.println(resp.getStatusLine().getStatusCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

private static byte[] File2byte(String filePath) {
    byte[] buffer = null;
    try
    {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1)
        {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return buffer;
}
private static String blobUri(String digest) {
    return String.format(Locale.ENGLISH,
            "http://%s:%s/_blobs/%s", "192.67.213.248", 4200, blobResourceUri("e_blobs", digest));
}
相關文章
相關標籤/搜索