Android4.4 + WebAPI for photo upload and android4.4webapi
There are many implementation methods for photo upload on the Internet. If you use the new android version to run it, you may find that it cannot be implemented at all. The main reason is that android 4.4 uses intent.ACTION_GET_CONTENTAfter the selector is enabled, the URI returned by getData () does not contain the actual file path, but is like "content: // com.android.providers.media.doc uments/document/image: 1234 ", so that the path of the image cannot be found in the traditional way. The simplest solution is to use intent.ACTION_PICKReplace intent.ACTION_GET_CONTENT. The following describes how to upload a photo after version 4.4:
Step 1: Click the photo button code
// Click btnHeadCamera. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View view) {Intent itCamera = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); startActivityForResult (itCamera, 0 );}});
Step 2: Save the photo and Image Code
@ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {switch (requestCode) {case 0: // photograph savePhoto (data); break;} super. onActivityResult (requestCode, resultCode, data );}
Final String SAVE_PATH = Environment. getExternalStorageDirectory () + "/my_head.jpg"; // Save the path after taking the photo
// Save the image
Public void savePhoto (Intent it) {Bundle bundle = it. getExtras (); if (bundle! = Null) {Bitmap photo = bundle. getParcelable ("data"); imgHead. setImageBitmap (photo); File fileHead = new File (SAVE_PATH); try {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {if (! FileHead. getParentFile (). exists () {fileHead. getParentFile (). mkdir ();} BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (fileHead); photo. compress (Bitmap. compressFormat. JPEG, 80, bos); bos. flush (); bos. close ();} else {Toast toast = Toast. makeText (HeadPhotoActivity. this, "Saving failed! ", Toast. LENGTH_SHORT); toast. setGravity (Gravity. CENTER, 0, 0); toast. show () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}
Step 3: Upload the Image Code
String SERVER_URL = Config. PhotoAPI + "/UploadImage"; // The API address of the uploaded Server
BtnHeadCancel. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View view) {new Thread (new Runnable () {@ Override public void run () {File file = new File (SAVE_PATH ); message msg = new Message (); msg. what = 0; if (file! = Null) {try {int re = ImageUtils. uploadForm (file, SERVER_URL); msg. obj = re;} catch (IOException ex) {msg. obj = 0; Toast. makeText (HeadPhotoActivity. this, "Upload Failed", Toast. LENGTH_SHORT ). show ();} handler. sendMessage (msg);} else {Toast. makeText (HeadPhotoActivity. this, "the uploaded image cannot be found", Toast. LENGTH_SHORT ). show ();}}}). start ();}});
Final Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case 0: if (int) msg. obj = 1) {Toast. makeText (HeadPhotoActivity. this, "uploaded successfully", Toast. LENGTH_SHORT ). show ();} else {Toast. makeText (HeadPhotoActivity. this, "Upload Failed", Toast. LENGTH_SHORT ). show () ;}break ;}}};
/***** @ Param uploadFile * File to be uploaded * @ param serverUrl * path of the uploaded server * @ throws IOException */public static int uploadForm (File uploadFile, String serverUrl) throws IOException {int re = 0; String fileName = uploadFile. getName (); StringBuilder sb = new StringBuilder (); sb. append ("--" + BOUNDARY + "\ r \ n"); sb. append ("Content-Disposition: form-data; name = \" "+ fileName +" \ "; filename = \" "+ fileName +" \ "" + "\ R \ n"); sb. append ("Content-Type: image/jpeg" + "\ r \ n"); sb. append ("\ r \ n"); byte [] headerInfo = sb. toString (). getBytes ("UTF-8"); byte [] endInfo = ("\ r \ n --" + BOUNDARY + "-- \ r \ n "). getBytes ("UTF-8"); System. out. println (sb. toString (); URL url = new URL (serverUrl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("POST"); conn. setRequestProperty ("Content- Type "," multipart/form-data; boundary = "+ BOUNDARY); conn. setRequestProperty ("Content-Length", String. valueOf (headerInfo. length + uploadFile. length () + endInfo. length); conn. setDoOutput (true); OutputStream out = conn. getOutputStream (); InputStream in = new FileInputStream (uploadFile); out. write (headerInfo); byte [] buf = new byte [1024]; int len; while (len = in. read (buf ))! =-1) out. write (buf, 0, len); out. write (endInfo); in. close (); out. close (); if (conn. getResponseCode () = 200) {re = 1;} return re ;}
Finally, the WebAPI code of the server is provided:
[HttpPost] public async Task <HttpResponseMessage> UploadImage (){
String filePath = "~ \ UploadFiles \ Photo "; // obtain the folder string dir = HttpContext. Current. Server. MapPath (filePath); // create the folder if (! Directory. Exists (dir) Directory. CreateDirectory (dir); if (! Request. content. isMimeMultipartContent ("form-data") {throw new HttpResponseException (HttpStatusCode. unsupportedMediaType);} var provider = new CustomMultipartFormDataStreamProvider (dir); try {// Read the form data. await Request. content. readAsMultipartAsync (provider); foreach (MultipartFileData file in provider. fileData) {// file. headers. contentDisposition. fileName; // file name before the file is uploaded // file. localFileName; // the uploaded file name Photo p = new Photo (); p. imgInfo = file. localFileName. substring (file. localFileName. lastIndexOf ("\"); p. sort = "Employee album"; p. addUser = "admin"; p. addTime = DateTime. now; p. url = filePath + p. imgInfo; db. photo. add (p); db. saveChanges ();} return Request. createResponse (HttpStatusCode. OK );
} Catch {return Request. CreateResponse (HttpStatusCode. BadRequest );
}}
// Rewrite the Upload File name public class CustomMultipartFormDataStreamProvider: MultipartFormDataStreamProvider {public CustomMultipartFormDataStreamProvider (string path): base (path) {} public override string GetLocalFileName (System. net. http. headers. httpContentHeaders headers) {string fileName = DateTime. now. toString ("yyyyMMddHHmmssfff"); return fileName + "_" + headers. contentDisposition. fileName. replace ("\" ", string. empty); // base. getLocalFileName (headers );}}