Recently, the WebService interface was written to provide data to clients and receive data from clients. When the data type is a file of a picture type, the file is converted to a stream and then encoded into a byte stream by Base64, and the string is transferred.
Client code:
public static void Main (string[] args) throws IOException {file File=new file ("D:/272.jpg"); FileInputStream fis = new FileInputStream (file); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buffer = new byte[1024]; int count = 0; while ((count = fis.read (buffer)) >= 0) {baos.write (buffer, 0, count); } String uploadbuffer = new String (Base64.encode (Baos.tobytearray ())); Carry out Base64 coding fis.close (); Writesmilfile (Uploadbuffer); System.out.println ("Uploadbuffer:" +uploadbuffer);} Write to txtpublic static void Writesmilfile (String content) {file File1 = new File ("D:/123.txt"); try {file1.createnewfile (); } catch (IOException e) {e.printstacktrace ();} PrintWriter pw;try {outputstreamwriter os = null; OS = new OutputStreamWriter (new FileOutputStream (File1), "UTF-8"); Os.write (content); Os.close ();} catch (IOException e) {e.printstacktrace ();}}
Server-side code:
Get the picture file from the client ( client processing is the file converted to stream BASE64 encoded into a string) public string getphotobyandroid (string photopath) {//Picture storage path Put to the formal need to modify string newfilepath= "d:/"; String newfilename =uuid.randomuuid (). toString () + "JPG"; FileOutputStream fos = null; Byte[] Buffer;try {buffer = new Base64decoder (). Decodebuffer (Photopath);//decode the image string from Android File DestDir = new File (Newfilepath); if (!destdir.exists ()) Destdir.mkdir (); FOS = new FileOutputStream (new File (Destdir,newfilename)); Save Picture fos.write (buffer); Fos.flush (); Fos.close (); } catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Upload picture Succeeded!" + newfilepath+newfilename); return newfilename;}
Solution for image file transfer between client Android and WebService