將文件下載並轉化爲base64編碼

需求:
通過定時任務生成pdf文件,並拿到pdf文件下載並轉化爲base64編碼通過接口返回給第三方

生成pdf的方式在上面的博客中已經寫過,後面還會更新更加完善的通過itext庫生成pdf的博客,這篇主要記述如何將文件下載並轉化爲base64編碼。

直接上代碼:

DefaultHttpClient httpClient = new DefaultHttpClient();
        InputStream in = null;
        HttpGet httpGet = null;
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        //獲取指定文件
        httpGet = new HttpGet("777.jpg");
        httpResponse = httpClient.execute(httpGet);
        entity = httpResponse.getEntity();
        in = entity.getContent();
        long length = entity.getContentLength();
        if (length <= 0) {
            System.out.println("下載的文件不存在");
        }
//        //下載文件”111“
//        File file = new File("/Users/wuyufei/Desktop/345.jpg");
//        FileOutputStream out1 = new FileOutputStream(file);
//        byte[] buffer2 = new byte[4096];
//        int readLength = 0;
//        while ((readLength = in.read(buffer2)) > 0) {
//            byte[] bytes = new byte[readLength];
//            System.arraycopy(buffer2, 0, bytes, 0, readLength);
//            out1.write(bytes);
//        }

        //轉化爲字節流
        ByteArrayOutputStream outStream = null;
        outStream = new ByteArrayOutputStream();
        byte[] buffer1 = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer1)) != -1) {
            outStream.write(buffer1, 0, len);
        }
        
        //字節流轉換爲base64編碼
        String sbbbase64 = java.util.Base64.getEncoder().encodeToString(outStream.toByteArray());
        //將base64編碼重新編譯爲圖片,查看是否正確”222“
        byte[] buffer = new BASE64Decoder().decodeBuffer(sbbbase64);
        FileOutputStream out = new FileOutputStream("/Users/wuyufei/Desktop/123.jpg");
        out.write(buffer);
//        out1.flush();
//        out1.close();
        in.close();
        out.close();
        outStream.close();

只需要直接將文件的url添加到httpget中就可以了

這段代碼中存在點問題,暫時未解決
問題:
註釋掉的下載文件的代碼和將base64編碼反編譯爲原文件的代碼不能同時存在,即代碼中的”111“和”222“部分代碼,如果同時存在那麼下載下來的文件即代碼中的345.jpg是沒有問題的,圖片進行轉base64編碼也沒有問題,但是在將base64編碼重新編譯爲圖片的時候即圖中的123.jpg文件的時候,會提示123.jpg文件是empty。暫未找到解決方式。

發佈了21 篇原創文章 · 獲贊 3 · 訪問量 3191
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章