Java uploads images to PHP files via HTTP protocol, and understands the PHP interface for uploading images to Android
Java files:
ImportJava.io.DataOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classHttpupload { Public Static FinalString api= "http://localhost/test.php"; Public Static voidMain (string[] args)throwsException {String Imgurl= "E:\\11.png"; String result=uploadimg (Imgurl); SYSTEM.OUT.PRINTLN (result); } Private StaticString uploadimg (String imgurl)throwsException {File imgfile=NewFile (Imgurl); URL URL=NewURL (API); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (10000); Conn.setrequestmethod ("POST"); Conn.setrequestproperty ("Content-type", "multipart/form-data; boundary=----123456789 "); Conn.setdoinput (true); Conn.setdooutput (true); OutputStream OS=NewDataOutputStream (Conn.getoutputstream ()); StringBuilder Body=NewStringBuilder (); Body.append ("------123456789\r\n"); Body.append ("Content-disposition:form-data; Name= ' img '; Filename= ' "+imgfile.getname () +" \ r \ n "); Body.append ("Content-type:image/jpeg\r\n\r\n"); Os.write (Body.tostring (). GetBytes ()); InputStream is=NewFileInputStream (Imgfile); byte[] b=New byte[1024]; intLen=0; while((Len=is.read (b))!=-1) {Os.write (b,0, Len); } String End= "\ r \ n------123456789--"; Os.write (End.getbytes ()); //output return resultInputStream input=Conn.getinputstream (); byte[] res=New byte[1024]; intreslen=Input.read (RES); return NewString (res,0, Reslen); }}
PHP file
<?PHPclasstest{ Public Static functionMain () {Header("Content-type:text/html;charset=utf-8"); if(!Empty($_files)){ $test=NewTest (); $test-uploadimg (); Exit; } } /** * Upload images*/ Public functionuploadimg () {$res=Move_uploaded_file($_files[' IMG '] [' Tmp_name '], './'.$_files[' IMG '] [' Name ']); if($res){ Echo"Upload Success"; }Else{ Echo"Upload Error"; }}}test::main ();? ><form enctype= "Multipart/form-data" action= "test.php" method= "POST" ><input type= "file" Name= "img"/ ><input type= "Submit" value= "Upload"/></form>
[Javase] Java upload image to PHP