There are two ways to upload images. One is to use the traditional HTML control and set the form attribute to multipart/form-data. This method is compatible with IE6 and IE7. Another method is to use data: URI to post the base64 encoding from the browser to the server, and then use base64 to decode it. This method is only applicable to modern browsers, such as ie9, chrome, Firefox, and safari. This article describes how to use data: URI to upload images.
Data URI format
The format of data URI is very simple. For details, see rfc2397. the basic format of data URI is as follows:
Data: [<MIME type>] [; charset = <charset>] [; base64], <encoded data>
In this format,
Data:
Is the protocol header of the URI, indicating that its resource is a data Uri. The second part, MIME type, indicates the data presentation format. For PNG images, the format is image/PNG. If not specified, the default format is text/plain. This character set (character set) is mostly ignored. If the specified data format is an image, the character set is no longer used. The next part indicates the data encoding method, we do not need to use base64 encoding format. If so, we will use the standard URL encoding method (such as the format of % XX); this encoded data section, it may contain spaces but does not matter.
Base 64 Encoding
Base64 is an encoding method that converts data into bit streams and maps them to a set of base64. Base64 contains A-Z, A-Z, natural number and +,/symbol. Equal Sign = indicates that we need to carry out padding ).
Processing code:
import java.io.FileOutputStream;import java.io.OutputStream;import sun.misc.BASE64Decoder;/** * to convert base64 string to a image * here we use it to handle data:uri * */public class Base64StringToImage{public boolean generateImage(String imageStr, String imageFilePath){if(imageStr == null){return false;}BASE64Decoder decoder = new BASE64Decoder(); try { // Base64 decodebyte[] bytes = decoder.decodeBuffer(imageStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) { bytes[i] += 256; } } // generate imageOutputStream out = new FileOutputStream(imageFilePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }}
Use Data: The URI upload method is simple ..