[JavaSE] uploading images to PHP using java and javase
Java uploads images to php files through http protocol, and its understanding of the php interface for Android to upload images
Java file:
Import java. io. dataOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. io. outputStream; import java.net. httpURLConnection; import java.net. URL; public class HttpUpload {public static final String API = "http: // localhost/test. php "; public static void main (String [] args) throws Exception {String imgUrl =" E: \ 11.png"; String result = uploadImg (imgUrl); Syst Em. out. println (result);} private static String uploadImg (String imgUrl) throws Exception {File imgFile = new File (imgUrl); URL url = new URL (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 = new DataOutputStream (conn. getOutputStream (); StringBuilder body = new StringBuilder (); 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"); OS. write (body. toString (). getBytes (); InputStream is = new FileInputStream (imgFile); byte [] B = new byte [1024]; I Nt len = 0; while (len = is. read (B ))! =-1) {OS. write (B, 0, len);} String end = "\ r \ n ------ 123456789 --"; OS. write (end. getBytes (); // output the returned result InputStream input = conn. getInputStream (); byte [] res = new byte [1024]; int resLen = input. read (res); return new String (res, 0, resLen );}}
PHP File
<? Phpclass Test {public static function main () {header ("content-type: text/html; charset = UTF-8"); if (! Empty ($ _ FILES) {$ test = new Test (); $ test-> uploadImg (); exit ;}} /*** upload image */public function uploadImg () {$ 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>