Created
November 22, 2017 05:37
-
-
Save riversun/9694fbda50e91a7059675eb9bf75839c to your computer and use it in GitHub Desktop.
Java Example: Convert A binary file to data URI in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import javax.xml.bind.DatatypeConverter; | |
public class ToDataURI { | |
public static void main(String[] args) throws IOException { | |
// source file | |
File file = new File("movie.mp4"); | |
// check content type of the file | |
String contentType = Files.probeContentType(file.toPath()); | |
// read data as byte[] | |
byte[] data = Files.readAllBytes(file.toPath()); | |
// convert byte[] to base64(java7) | |
String base64str = DatatypeConverter.printBase64Binary(data); | |
// convert byte[] to base64(java8) | |
// String base64str = Base64.getEncoder().encodeToString(data); | |
// cretate "data URI" | |
StringBuilder sb = new StringBuilder(); | |
sb.append("data:"); | |
sb.append(contentType); | |
sb.append(";base64,"); | |
sb.append(base64str); | |
System.out.println(sb.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THE FILE MUST BE UPLOADED?