php - Android file upload - $_FILES returns empty -
i'm trying upload image android app server php script. http response returns status ok: 200, $_files["upfile"]["name"] returns empty. i`ve checked folders permissions , aready 777.
my .java class
/********************upload data*************************************/ class uploadimg extends asynctask<void, void, void>{ networkinfo net; messaging uactivity; httpurlconnection connection = null; dataoutputstream outputstream = null; datainputstream inputstream = null; string folderpath; string arrayoffiles[]; file root; file allfiles; string urlserver = "http://bmcpublicidade.com.br/chat/upload.php"; string lineend = "\r\n"; string twohyphens = "--"; string boundary = "*****"; int bytesread, bytesavailable, buffersize; byte[] buffer; int maxbuffersize = 10*1024*1024; url url; progressdialog pdialog = new progressdialog(messaging.this); @override protected void onpreexecute() { log.d(" uploadimg","onprerequest"); pdialog.setmessage("uploading gps data. please wait..."); pdialog.setindeterminate(false); pdialog.setcancelable(true); pdialog.show(); } @override protected void doinbackground(void... params) { log.d(" uploaddata","doinbackground"); string filename = ""+selectedpath; httpurlconnection conn = null; dataoutputstream dos = null; bufferedreader instream = null; string lineend = "rn"; string twohyphens = "--"; string boundary = "*****"; int bytesread, bytesavailable, buffersize; byte[] buffer; int maxbuffersize = 10*1024*1024; string responsefromserver = ""; string urlstring = "http://bmcpublicidade.com.br/chat/upload.php"; try { //------------------ client request fileinputstream fileinputstream = new fileinputstream(new file(selectedpath) ); // open url connection servlet url url = new url(urlstring); // open http connection url conn = (httpurlconnection) url.openconnection(); // allow inputs conn.setdoinput(true); // allow outputs conn.setdooutput(true); // don't use cached copy. conn.setusecaches(false); // use post method. 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("upfile", filename); dos = new dataoutputstream( conn.getoutputstream() ); dos.writebytes(twohyphens + boundary + lineend); dos.writebytes("content-disposition: form-data; name=\"upfile\"; filename='"+ selectedpath +"'" + 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("upfile", "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" +" http://**********/media/uploads/"; messagetext.settext(msg); toast.maketext(messaging.this, "file upload complete.", toast.length_short).show(); } }); } // close streams log.e("debug","gravando arquivo: " + filename); fileinputstream.close(); dos.flush(); dos.close(); } catch (malformedurlexception ex) { log.e("debug", "erro: " + ex.getmessage(), ex); } catch (ioexception ioe) { log.e("debug", "erro: " + ioe.getmessage(), ioe); } //------------------ read server response try { instream = new bufferedreader ( new inputstreamreader(conn.getinputstream()) ); string str; while (( str = instream.readline()) != null) { log.e("debug","servidor diz: "+str); } instream.close(); } catch (ioexception ioex){ log.e("debug", "erro: " + ioex.getmessage(), ioex); } return null; } @override protected void onpostexecute(void result) { log.d(" uploadmsg","onpost"); pdialog.dismiss(); messagetext.settext("uploaded"); } } /********************end of upload*************************************/
and here php file
// file going placed $target_path = "uploads/"; /* add original filename our target path. result "/uploads/filename.extension" */ $target_path = $target_path . basename( $_files['upfile']['name']); if( $_files['upfile'] ) { if(move_uploaded_file($_files['upfile']['tmp_name'], $target_path)) { // $qry = "update users set image=".$target_path." username='$username'"; // $db->query($qry); echo "o arquivo ". basename( $_files['upfile']['name']). " está sendo enviado"; } else{ echo "ocorreu um erro ao realizar envio de arquivo, por favor tente novamente!\n"; echo "nome arquivo: " . basename( $_files['upfile']['name'])."\n"; echo "target_path: " .$target_path; } }else { echo "nenhum arquivo careregado!"; /*** ever enters here!!! ***/ }
can me?
thanks !!!
i've encountered same issue. posting file succeeds 200 response, _files empty. fixed issue specifying content-length header. e.g.:
conn.setrequestproperty("content-length", integer.tostring(fileinputstream.available()));
edit: so, when using this, file appeared in _files error code of 3. however, had call conn.setchunkedstreamingmode(1024);. removing content-length , call setchunkedstreamingmode worked me, i'm pretty sure empty _files content-length field not being set correctly.
Comments
Post a Comment