httpserver - android and sending files to HTTP server -
i try write application send file http server. here android-side code:
public void send(view view) { httpurlconnection connection = null; dataoutputstream outputstream = null; datainputstream inputstream = null; string pathtoourfile = "/data/file.txt"; string urlserver = "http://localhost/zad1.php"; string lineend = "\r\n"; string twohyphens = "--"; string boundary = "*****"; int bytesread, bytesavailable, buffersize; byte[] buffer; int maxbuffersize = 1*1024*1024; try { fileinputstream fileinputstream = new fileinputstream(new file(pathtoourfile) ); url url = new url(urlserver); connection = (httpurlconnection) url.openconnection(); // allow inputs & outputs connection.setdoinput(true); connection.setdooutput(true); connection.setusecaches(false); // enable post method connection.setrequestmethod("post"); connection.setrequestproperty("connection", "keep-alive"); connection.setrequestproperty("content-type", "multipart/form-data;boundary="+boundary); outputstream = new dataoutputstream( connection.getoutputstream() ); outputstream.writebytes(twohyphens + boundary + lineend); outputstream.writebytes("content-disposition: form-data; name=\"uploadedfile\";filename=\"" + pathtoourfile +"\"" + lineend); outputstream.writebytes(lineend); bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); buffer = new byte[buffersize]; // read file bytesread = fileinputstream.read(buffer, 0, buffersize); while (bytesread > 0) { outputstream.write(buffer, 0, buffersize); bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); bytesread = fileinputstream.read(buffer, 0, buffersize); } outputstream.writebytes(lineend); outputstream.writebytes(twohyphens + boundary + twohyphens + lineend); // responses server (code , message) int serverresponsecode = connection.getresponsecode(); string serverresponsemessage = connection.getresponsemessage(); fileinputstream.close(); outputstream.flush(); outputstream.close(); log.i("odpowiedz", serverresponsemessage); } catch (exception ex) { log.i("wyjatek", ex.getmessage()); } }
}
and here php script
<?php $target_path = "./"; $target_path = $target_path . basename( $_files['uploadedfile']['name']); if(move_uploaded_file($_files['uploadedfile']['tmp_name'], $target_path)) { echo "the file ". basename( $_files['uploadedfile']['name'])." has been uploaded"; } else { echo "there error uploading file, please try again!"; } ?>
my problem when try send file server "localhost/127.0.0.1:80 - connection refused" exception. of know doing wrong? every , tip.
use import org.apache.http.entity.mime.multipartentity;
Comments
Post a Comment