php - Issue with uploading image from Android to Mysql -


i'm working on social app , want upload image in database, tried code , worked. file in folder problem path couldn't mysql database figured out $_files['uploaded_file']['name'] empty don't know how solve this.

addstatus.java :

public class addstatus extends appcompatactivity implements view.onclicklistener  { private progressdialog pdialog; edittext status; button send,upload_img; string user_id; private textview messagetext; private imageview imageview; private int serverresponsecode = 0; private progressdialog dialog = null; private string imagepath=null; jsonparser jsonparser = new jsonparser(); private static final string uploadserveruri = "http://192.168.1.10/social/addstatus.php";  private static final string tag_success = "success"; private static final string tag_message = "message";  protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.add_status);      imageview img= new imageview(this);      status =(edittext)findviewbyid(r.id.edt_status);     send = (button)findviewbyid(r.id.btn_send);     upload_img = (button) findviewbyid(r.id.btn_img);      messagetext  = (textview)findviewbyid(r.id.messagetext);     imageview = (imageview)findviewbyid(r.id.imageview_pic);     send.setonclicklistener(this);     upload_img.setonclicklistener(this);      final intent callingintent = getintent();     user_id = callingintent.getstringextra("user_id");   } @override public void onclick(view v) {     switch (v.getid()) {         case r.id.btn_send:              dialog = progressdialog.show(addstatus.this, "", "uploading file...", true);             messagetext.settext("uploading started.....");             new thread(new runnable() {                 public void run() {                      uploadfile(imagepath);                  }             }).start();              string stat = status.gettext().tostring();             long ts = system.currenttimemillis();             string time = ts.tostring();             new addstatus().execute(stat,user_id,time);              break;          case r.id.btn_img:             intent intent = new intent();             intent.settype("image/*");             intent.setaction(intent.action_get_content);             startactivityforresult(intent.createchooser(intent, "complete action using"), 1);             break;          default:             break;     }  }   @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(addstatus.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(addstatus.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(addstatus.this, "got exception : see logcat ", toast.length_short).show();                 }             });         }         dialog.dismiss();         return serverresponsecode;      } // end else block }  public void onpause() {      super.onpause();     if (pdialog != null)         pdialog.dismiss(); } class addstatus extends asynctask<string, string, string> {      protected void onpreexecute() {         super.onpreexecute();         pdialog = new progressdialog(addstatus.this);         pdialog.setmessage("creating user...");         pdialog.setindeterminate(false);         pdialog.setcancelable(true);         pdialog.show();     }      @override     protected string doinbackground(string... args) {         int success;         string status = args[0];         string user_id = args[1];         string time = args[2];          try {             // building parameters             list<namevaluepair> params = new arraylist<namevaluepair>();             params.add(new basicnamevaluepair("status", status));             params.add(new basicnamevaluepair("user_id", user_id));             params.add(new basicnamevaluepair("time", time));                log.d("request!", "starting");              // getting product details making http request             jsonobject json = jsonparser.makehttprequest(                     uploadserveruri, "post", params);              // check log json response             log.d("login attempt", json.tostring());              // json success tag             success = json.getint(tag_success);             if (success == 1) {                 log.d("user created!", json.tostring());                 return json.getstring(tag_message);             } else {                 log.d("login failure!", json.getstring(tag_message));              }         } catch (jsonexception e) {             e.printstacktrace();         }           return null;     }       protected void onpostexecute(string file_url) {         // dismiss dialog once product deleted         pdialog.dismiss();         if (file_url != null) {             toast.maketext(addstatus.this, file_url, toast.length_long).show();         }     }  }   } 

addstatus.php

<?php   error_reporting(e_all ^ e_deprecated);    $response = array();      $target_path = "";     $file_upload_url = 'http://' . '192.168.1.10' . '/' . 'social' . '/' .             $target_path;     if (isset($_files['uploaded_file']['name'])) {  $target_path = $target_path . basename($_files['uploaded_file']['name']);   $response['file_name'] = basename($_files['uploaded_file']['name']);   try {     // throws exception incase file not being moved     if (!move_uploaded_file($_files['uploaded_file']['tmp_name'], $target_path)) {         // make error flag true         $response['error'] = true;         $response['message'] = 'could not move file!';     }      // file uploaded     $response['message'] = 'file uploaded successfully!';     $response['error'] = false;     $response['file_path'] = $file_upload_url . basename($_files['uploaded_file']['name']);     $path = $file_upload_url . basename($_files['uploaded_file']['name']);  } catch (exception $e) {     // exception occurred. make error flag true     $response['error'] = true;     $response['message'] = $e->getmessage(); } } else {   // file parameter missing $response['error'] = true; $response['message'] = 'not received file!f'; }        if (isset($_post['user_id']) && isset($_post['status']) && isset($_post['time'])){   $status = $_post['status']; $user_id = $_post['user_id']; $time = $_post['time'];     require_once __dir__ . '/db_connect.php';  // connecting db $db = new db_connect();     $result = mysql_query("insert posts(user_id,text,time,image) values('$user_id','$status','$time','$path')");        if ($result) {         $response["success"] = 1;         $response["message"] = "user created";          echo json_encode($response);             }     else {         $response["success"] = 0;         $response["message"] = "registration failed";          echo json_encode($response);      } } else { // required field missing $response["success"] = 0; $response["message"] = "required field(s) missing";  // echoing json response echo json_encode($response); }  ?> 

i hope can me issue. thanks.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

post - imageshack API cURL -

dataset - MPAndroidchart returning no chart Data available -