In our work sometimes we need to convert a picture or PDF file to a Base64 encoding, and then download it from the server side to the local, where I enumerate the conversion methods between the two:
Convert BASE64 encoding to PDF:
/** * Description: Convert base64 encoded content to PDF * @param base64 encoded content, file storage path (with file name) * @Author Fuyuwe I * Create date:2015 July 30 Morning 9:40:23 * * Public Static void base64stringtopdf(String base64content,string FilePath) {Base64decoder decoder =NewBase64decoder (); Bufferedinputstream bis =NULL; FileOutputStream fos =NULL; Bufferedoutputstream BOS =NULL;Try{byte[] bytes = Decoder.decodebuffer (base64content);//base64 encoded content into a byte arrayBytearrayinputstream Byteinputstream =NewBytearrayinputstream (bytes); bis =NewBufferedinputstream (Byteinputstream); File File =NewFile (FilePath); File path = File.getparentfile ();if(!path.exists ()) {Path.mkdirs (); } FOS =NewFileOutputStream (file); BOS =NewBufferedoutputstream (FOS);byte[] buffer =New byte[1024x768];intLength = bis.read (buffer); while(Length! =-1) {bos.write (buffer,0, length); Length = bis.read (buffer); } bos.flush (); }Catch(Exception e) {E.printstacktrace (); }finally{closestream (bis, FOS, BOS); } }
Convert PDF to BASE64 encoding:
/** * Description: Convert PDF file to Base64 encoding * @param PDF file to be transferred * @Author Fuyuwei * Create date:2015 August 3 pm 9:52:30 * * Public StaticStringPDFToBase64(File file) {Base64encoder encoder =NewBase64encoder (); FileInputStream fin =NULL; Bufferedinputstream bin =NULL; Bytearrayoutputstream BAOs =NULL; Bufferedoutputstream bout =NULL;Try{fin =NewFileInputStream (file); Bin =NewBufferedinputstream (Fin); BAOs =NewBytearrayoutputstream (); bout =NewBufferedoutputstream (BAOs);byte[] buffer =New byte[1024x768];intLen = bin.read (buffer); while(Len! =-1) {bout.write (buffer,0, Len); Len = bin.read (buffer); }//refreshes this output stream and forces all buffered output bytes to be written outBout.flush ();byte[] bytes = Baos.tobytearray ();returnEncoder.encodebuffer (bytes). Trim (); }Catch(FileNotFoundException e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }finally{Try{Fin.close (); Bin.close (); Bout.close (); }Catch(IOException e) {E.printstacktrace (); } }return NULL; }
When we use these two classes directly, Eclipse will make an error:
Base64encoder encoder = new Sun.misc.BASE64Encoder ();
Base64decoder decoder = new Sun.misc.BASE64Decoder ();
Here's how to fix it:
Right-click the project-->build path-–>configure build Path
Click OK to save
Conversion between PDF and BASE64 encoding