Directly on the code, okay?
Method Name:
Generateimage
To pass the parameter:
Base64img: Uploaded Base64 code
Realpath: The resulting picture path
Imgtypes: Picture Type
String imgBase64 = Request.getparameter ("userImgbase64");
Get Current server path
String Realpath = Request.getservletcontext (). Getrealpath ("") + "\\img";
System.out.println (); http://192.168.191.1:8080/MyWeb/img
string[] Imgtype = Imgbase64.split (",");
Get the picture type (if there is no type, it looks like an error)
String imgtypes = imgtype[0].tostring (). substring (one, imgtype[0].tostring (). Length ()-7);
String userImgbase64 = Generateimage (imgbase64,realpath,imgtypes);
System.out.println (Realpath); Http://192.168.191.1:8080/MyWeb/img/1532493648717.png
//Base64 decoding a byte array string and generating a picture Public Staticstring Generateimage (String base64img,string realpath,string imgtypes) {string Ret_filename=NULL; //Temporary file pathFile File_normer =NewFile (realpath+ "/"); if(!file_normer.exists ()) {File_normer.mkdirs (); } if(Base64img = =NULL)//image data is empty return"Image data is empty"; Base64img= Base64img.replaceall ("data:image/" +imgtypes+ "; base64," "," "); Base64decoder Decoder=NewBase64decoder (); Try { //Base64 decoding byte[] B =Decoder.decodebuffer (BASE64IMG); for(inti = 0; i < b.length; ++i) {if(B[i] < 0) {//Adjust Exception DataB[i] + = 256; } } //Create a JPEG pictureRet_filename = System.currenttimemillis () + "." +imgtypes+ ""; File File=NewFile (Realpath + "/" +ret_filename); OutputStream out=Newfileoutputstream (file); Out.write (b); Out.flush (); Out.close (); } Catch(Exception e) {e.printstacktrace (); } returnRet_filename; }
Java upload different types of images, save the database (Base64 bitmap to network picture)