How can send images from Android Application to Server? -


i want store images in server via post, images sent sent local storage cell, code asynchronous class in android :

class imageupload extends asynctask<void, void, string>{      @override     protected string doinbackground(void... var) {         system.out.println(incidentid);         httpurlconnection connection = null;         dataoutputstream outputstream = null;         inputstream inputstream = null;          string twohyphens = "--";         string boundary = "*****" + long.tostring(system.currenttimemillis()) + "*****";         string lineend = "\r\n";          string result = "";          int bytesread, bytesavailable, buffersize;         byte[] buffer;         int maxbuffersize = 1 * 1024 * 1024;          string[] q = mcurrentphotopath.split("/");         int idx = q.length - 1;          try {             file file = new file(mcurrentphotopath);             fileinputstream fileinputstream = new fileinputstream(file);              url url = new url(url_add_attachment);             connection = (httpurlconnection) url.openconnection();              connection.setdoinput(true);             connection.setdooutput(true);             connection.setusecaches(false);              connection.setrequestmethod("post");             connection.setrequestproperty("content-type", "multipart/form-data; charset=utf-8");             connection.setrequestproperty("accept", "application/json");              outputstream = new dataoutputstream(connection.getoutputstream());             outputstream.writebytes(twohyphens + lineend);             outputstream.writebytes("content-disposition: form-data; name=\"" + "file" + "\"; filename=\"" + q[idx] + "\"" + lineend);             outputstream.writebytes("content-type: " + "image" + lineend);             outputstream.writebytes("content-transfer-encoding: binary" + lineend);              outputstream.writebytes(lineend);              bytesavailable = fileinputstream.available();             buffersize = math.min(bytesavailable, maxbuffersize);             buffer = new byte[buffersize];              bytesread = fileinputstream.read(buffer, 0, buffersize);             outputstream.write(buffer, 0, buffersize);             bytesavailable = fileinputstream.available();             buffersize = math.min(bytesavailable, maxbuffersize);             bytesread = fileinputstream.read(buffer, 0, buffersize);              outputstream.writebytes(lineend);             try {                 outputstream.writebytes(twohyphens + lineend);                 //outputstream.writebytes("content-disposition: form-data; name=\"" + key + "\"" + lineend);                 outputstream.writebytes("content-type: text/plain" + lineend);                 outputstream.writebytes(lineend);                 outputstream.writebytes(lineend);                 //}                  outputstream.writebytes(twohyphens + twohyphens + lineend);             } catch (exception e) {                 e.printstacktrace();             }             int status = connection.getresponsecode();              inputstream in;             if(status >= httpstatus.sc_bad_request)                 in = connection.geterrorstream();             else                 in = connection.getinputstream();              inputstream = connection.getinputstream();              result = convertstreamtostring(in);              fileinputstream.close();             inputstream.close();             outputstream.flush();             outputstream.close();           }catch(exception e){             e.printstacktrace();         }          return result;      } } 

the server throws 400 error response send me exception :

java.io.filenotfoundexception: http://10.0.2.2/app_dev.php/incidents/8/attachments 

mainactivity.java

import java.io.dataoutputstream; import java.io.file; import java.io.fileinputstream; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.url;  import android.app.activity; import android.app.progressdialog; import android.content.intent; import android.database.cursor; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.net.uri; import android.os.bundle; import android.provider.mediastore; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.imageview; import android.widget.textview; import android.widget.toast;  public class mainactivity extends activity implements onclicklistener{      private textview messagetext;     private button uploadbutton, btnselectpic;     private imageview imageview;     private int serverresponsecode = 0;     private progressdialog dialog = null;      private string uploadserveruri = null;     private string imagepath=null;     @override     public void oncreate(bundle savedinstancestate) {          super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);          uploadbutton = (button)findviewbyid(r.id.uploadbutton);         btnselectpic = (button)findviewbyid(r.id.button_selectpic);         messagetext  = (textview)findviewbyid(r.id.messagetext);         imageview = (imageview)findviewbyid(r.id.imageview_pic);          btnselectpic.setonclicklistener(this);         uploadbutton.setonclicklistener(this);         uploadserveruri = "http://10.0.2.2/uploads/uploadtoserver.php";         imageview img= new imageview(this);      }       @override     public void onclick(view arg0) {         if(arg0==btnselectpic)         {             intent intent = new intent();             intent.settype("image/*");             intent.setaction(intent.action_get_content);             startactivityforresult(intent.createchooser(intent, "complete action using"), 1);         }         else if (arg0==uploadbutton) {               dialog = progressdialog.show(mainactivity.this, "", "uploading file...", true);              messagetext.settext("uploading started.....");              new thread(new runnable() {                  public void run() {                        uploadfile(imagepath);                   }                }).start();              }      }       @override     protected void onactivityresult(int requestcode, int resultcode, intent data) {          if (requestcode == 1 && resultcode == result_ok) {             //bitmap photo = (bitmap) data.getdata().getpath();               uri selectedimageuri = data.getdata();             imagepath = getpath(selectedimageuri);             bitmap bitmap=bitmapfactory.decodefile(imagepath);             imageview.setimagebitmap(bitmap);             messagetext.settext("uploading file path:" +imagepath);          }     }          public string getpath(uri uri) {                 string[] projection = { mediastore.images.media.data };                 cursor cursor = managedquery(uri, projection, null, null, null);                 int column_index = cursor.getcolumnindexorthrow(mediastore.images.media.data);                 cursor.movetofirst();                 return cursor.getstring(column_index);             }      public int uploadfile(string sourcefileuri) {             string filename = sourcefileuri;            httpurlconnection conn = null;           dataoutputstream dos = null;             string lineend = "\r\n";           string twohyphens = "--";           string boundary = "*****";           int bytesread, bytesavailable, buffersize;           byte[] buffer;           int maxbuffersize = 1 * 1024 * 1024;            file sourcefile = new file(sourcefileuri);             if (!sourcefile.isfile()) {                 dialog.dismiss();                  log.e("uploadfile", "source file not exist :"+imagepath);                 runonuithread(new runnable() {                    public void run() {                        messagetext.settext("source file not exist :"+ imagepath);                    }                });                  return 0;            }           else           {                try {                        // open url connection servlet                    fileinputstream fileinputstream = new fileinputstream(sourcefile);                    url url = new url(uploadserveruri);                     // open http  connection  url                    conn = (httpurlconnection) url.openconnection();                     conn.setdoinput(true); // allow inputs                    conn.setdooutput(true); // allow outputs                    conn.setusecaches(false); // don't use cached copy                    conn.setrequestmethod("post");                    conn.setrequestproperty("connection", "keep-alive");                    conn.setrequestproperty("enctype", "multipart/form-data");                    conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary);                    conn.setrequestproperty("uploaded_file", filename);                      dos = new dataoutputstream(conn.getoutputstream());                     dos.writebytes(twohyphens + boundary + lineend);                     dos.writebytes("content-disposition: form-data; name=\"uploaded_file\";filename=\""                                              + filename + "\"" + lineend);                     dos.writebytes(lineend);                     // create buffer of  maximum size                    bytesavailable = fileinputstream.available();                      buffersize = math.min(bytesavailable, maxbuffersize);                    buffer = new byte[buffersize];                     // read file , write form...                    bytesread = fileinputstream.read(buffer, 0, buffersize);                       while (bytesread > 0) {                       dos.write(buffer, 0, buffersize);                      bytesavailable = fileinputstream.available();                      buffersize = math.min(bytesavailable, maxbuffersize);                      bytesread = fileinputstream.read(buffer, 0, buffersize);                         }                     // send multipart form data necesssary after file data...                    dos.writebytes(lineend);                    dos.writebytes(twohyphens + boundary + twohyphens + lineend);                     // responses server (code , message)                    serverresponsecode = conn.getresponsecode();                    string serverresponsemessage = conn.getresponsemessage();                     log.i("uploadfile", "http response : "                             + serverresponsemessage + ": " + serverresponsecode);                     if(serverresponsecode == 200){                         runonuithread(new runnable() {                             public void run() {                                 string msg = "file upload completed.\n\n see uploaded file here : \n\n"                                       +" f:/wamp/wamp/www/uploads";                                 messagetext.settext(msg);                                 toast.maketext(mainactivity.this, "file upload complete.", toast.length_short).show();                             }                         });                                    }                         //close streams //                    fileinputstream.close();                    dos.flush();                    dos.close();                } catch (malformedurlexception ex) {                    dialog.dismiss();                     ex.printstacktrace();                    runonuithread(new runnable() {                       public void run() {                           messagetext.settext("malformedurlexception exception : check script url.");                           toast.maketext(mainactivity.this, "malformedurlexception", toast.length_short).show();                       }                   });                    log.e("upload file server", "error: " + ex.getmessage(), ex);                 } catch (exception e) {                    dialog.dismiss();                     e.printstacktrace();                    runonuithread(new runnable() {                       public void run() {                           messagetext.settext("got exception : see logcat ");                           toast.maketext(mainactivity.this, "got exception : see logcat ", toast.length_short).show();                       }                   });                   log.e("upload file server exception", "exception : "  + e.getmessage(), e);                 }               dialog.dismiss();                      return serverresponsecode;              } // end else block           }   } 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>  <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="vertical"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      >       <imageview          android:id="@+id/imageview_pic"          android:layout_width="100dp"          android:layout_height="100dp"          android:layout_gravity="center"          android:src="@drawable/ic_launcher" />       <button          android:id="@+id/button_selectpic"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="select picture" />       <button          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:text="click upload file"          android:id="@+id/uploadbutton"      />       <textview          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:text=""          android:id="@+id/messagetext"          android:textcolor="#000000"          android:textstyle="bold"      />    </linearlayout> 

mainfest file::

 <uses-permission android:name="android.permission.internet"/> 

uploadtoserver.php

<?php  $file_path = "../image upload folder name here/";  $file_path = $file_path . basename( $_files['uploaded_file']['name']); if(move_uploaded_file($_files['uploaded_file']['tmp_name'], $file_path)) {    // echo "success"; } else{   //  echo "fail"; } ?> 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -