java - Upload Image On Php Server In Android Programically -
i trying upload images android php server server working ios using objective c in android did not not know how upload images. have tried below code server returns message (images not in proper format or missing image file
arraylist<file> imagefiles= new arraylist<file>(); for(int i=0;i<mcameradatalist.size();i++) { file f = new file(getfilesdir(),"image"+i+".jpg"); f.createnewfile(); bitmap bitmap = bitmap.createscaledbitmap( bitmapfactory.decodebytearray(mcameradatalist.get(i), 0, mcameradatalist.get(i).length),commonmethods.getdevicewidth(this), commonmethods.getdeviceheight(this), true); bytearrayoutputstream stream = new bytearrayoutputstream(); bitmap.compress(bitmap.compressformat.jpeg, 90, stream); byte[] bitmapdata = stream.tobytearray(); fileoutputstream fos = new fileoutputstream(f); fos.write(bitmapdata); fos.flush(); fos.close(); imagefiles.add(f); } public static void postproduct(arraylist<file> nimages) throws unsupportedencodingexception { multipartentitybuilder entity=multipartentitybuilder.create(); entity.setmode(httpmultipartmode.browser_compatible); entity.addpart("authenticity",new stringbody("1")); entity.addpart("brand_id",new stringbody("1")); entity.addpart("cat_id",new stringbody("2")); entity.addpart("color_id1",new stringbody("2")); entity.addpart("color_id2",new stringbody("3")); entity.addpart("condition_id",new stringbody("3")); entity.addpart("description",new stringbody("bgvv")); entity.addpart(constants.keyvalues.device_id,new stringbody(constants.device_id)); entity.addpart("images",new stringbody("images")); entity.addpart("lon",new stringbody("74.344630")); entity.addpart("lat",new stringbody("31.516762")); entity.addpart("name_brand",new stringbody("2 puffs")); entity.addpart("package_size",new stringbody("0")); entity.addpart("selling_price", new stringbody("20")); entity.addpart("title",new stringbody("my test")); entity.addpart(constants.keyvalues.uid,new stringbody(string.valueof(commonobjects.getuserprofile().getuid()))); for(int i=0;i<nimages.size();i++) { file f=new file(nimages.get(i).getabsolutepath()); if(f.exists()){ entity.addpart(constants.keyvalues.images, new filebody(f, "image/jpeg")); } } new setdatatoserver(constants.networkservicemethods.product.post_product, entity, new setdatatoserver.setdatanotifier() { @override public void ondatareceived(boolean iserror, string message, jsonobject jsonobj) { arraylist<string> postproductresult =new arraylist<string>(); try { log.e("json",jsonobj.tostring()); if (!jsonobj.isnull(constants.keyvalues.data)) { jsonobject jsonobjectdata = jsonobj.getjsonobject(constants.keyvalues.data); // postproductresult.add(jsonobjectdata.getstring(constants.keyvalues.con_id)); // postproductresult.add(jsonobjectdata.getstring(constants.keyvalues.order_id)); } } catch (jsonexception e) { iserror = true; message = "sorry! error occurred in data parsing"; } producthandlermethods.onpostproductresult(iserror, message, postproductresult); } }).callservertosetdata(); }
can body tell doing wrong.
server side code
public function postproduct_post() { $brand_id = $this->post('brand_id'); if ($brand_id == '') { $brand_name = $this->post('name_brand'); if ($brand_name == '') $this->create_error(-1); $brand_id = $this->mproduct->insertbrandname($brand_name); } else { if (!$this->mproduct->_checkbrandid($brand_id)) $this->create_error(-15, 'brand_id'); } $time = time(); $uid = $this->post('uid'); $cat_id = $this->post('cat_id'); $title = $this->post('title'); $description = $this->post('description'); $condition_id = $this->post('condition_id'); $authenticity = $this->post('authenticity'); $color_id1 = $this->post('color_id1', 0); $color_id2 = $this->post('color_id2', 0); $selling_price = $this->post('selling_price'); $package_size = $this->post('package_size'); $lat = $this->post('lat'); $lon = $this->post('lon'); if ($uid == '' || $cat_id == '' || $title == '' || $description == '' || $color_id1 == '' || $condition_id == '' || $authenticity == '') { $this->create_error(-1); } if (!$this->muser->_checkuid($uid)) $this->create_error(-10); if (!$this->mproduct->_checkcatid($cat_id)) $this->create_error(-15, 'cat_id'); if ($color_id1 > 0 && !$this->mproduct->_checkcolorid($color_id1)) { $this->create_error(-15, 'color_id1'); } if ($color_id2 > 0 && !$this->mproduct->_checkcolorid($color_id2)) { $this->create_error(-15, 'color_id2'); } $images = isset($_files['images']) ? $_files['images'] : null; if ($images == null || count($images['name']) <= 0) { $this->create_error(-21); } $this->load->model('mfile'); if (!$this->mfile->checkarrayimage($images)) { $this->create_error(-13); } if (!$this->mproduct->_checkconditionid($condition_id)) { $this->create_error(-15, 'condition_id'); } $params = array(); $params['owner_id'] = $uid; $params['cat_id'] = $cat_id; $params['title'] = $title; $params['added'] = $time; $params['brand_id'] = $brand_id; $params['description'] = $description; $params['is_sell'] = 1; $params['size_id'] = 101; $params['is_swap'] = 0; $params['is_give'] = 0; $params['color_id1'] = $color_id1; $params['color_id2'] = $color_id2; $params['condition_id'] = $condition_id; $params['authenticity'] = $authenticity; $params['lat'] = $lat; $params['lon'] = $lon; $params['last_activity'] = $time; $params['last_comment'] = ''; $params['status'] = 1; if ($selling_price != '') $params['selling_price'] = $selling_price; if ($package_size != '') $params['package_size'] = $package_size; $product_id = $this->mproduct->insertproduct($params); if ($product_id == -1) { $this->create_error(-16); } $paths = $this->mfile->savearrayimage($images, $product_id, $time); if (count($paths) <= 0) { $this->create_error(-13); } $params = array(); $params['image'] = $this->mfile->createthumbproduct($paths[0]); $params['status'] = 1; $this->mproduct->updateafterinsertproduct($product_id, $params); $this->mproduct->upitemincat($cat_id); $this->mproduct->upiteminbrand($brand_id); $this->muser->upitemofuser($uid); $this->mproduct->insertproductimage($product_id, $paths); //$this->mfeed->insertnotifynewproduct($time, $uid, $product_id); //$this->mpush->createnotiaddproduct($uid, $product_id); $uids = $this->mproduct->getuidsfollowuser($uid); $this->load->model('mnotify'); $this->mnotify->createnotifymany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid)); $this->mfeed->insertfeedwhensell($time, $product_id); $data = array(); $data['product_id'] = $product_id; $this->create_success($data, 'add success'); }
try upload image via below service written in android, make sure image path correct in below code, place image in sdcard :
public class myservice extends service { sharedpreferences sharedpref; sharedpreferences.editor editor; int serverresponsecode = 0; string uploadserveruri = null; private static final string tag = "com.example.serviceexample"; @override public void oncreate() { log.i(tag, "service oncreate"); sharedpref = getsharedpreferences("myfiles", mode_private); /************* php script path ****************/ uploadserveruri = "http://myserver/uploadimage.php"; } @override public int onstartcommand(intent intent, int flags, int startid) { log.i(tag, "service onstartcommand " + startid); final int currentid = startid; runnable r = new runnable() { public void run() { (int = 0; < 3; i++) { // long endtime = system.currenttimemillis() + 10*1000; // while (system.currenttimemillis() < endtime) { synchronized (this) { try { uploadfile(sharedpref.getstring(i + "", "")); } catch (exception e) { } } // } log.i(tag, "service running " + currentid); } stopself(); } }; thread t = new thread(r); t.start(); return service.start_sticky; } @override public ibinder onbind(intent arg0) { // todo auto-generated method stub log.i(tag, "service onbind"); return null; } @override public void ondestroy() { log.i(tag, "service ondestroy"); } 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(environment.getexternalstoragedirectory(),sourcefileuri); file sourcefile = new file(environment.getexternalstoragedirectory() .getabsolutepath() + "/" + filename); if (!sourcefile.isfile()) { 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("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) { } // close streams // fileinputstream.close(); dos.flush(); dos.close(); } catch (malformedurlexception ex) { ex.printstacktrace(); log.e("upload file server", "error: " + ex.getmessage(), ex); } catch (exception e) { e.printstacktrace(); log.e("upload file server exception", "exception : " + e.getmessage(), e); } return serverresponsecode; } // end else block } }
Comments
Post a Comment