How to handle Server side HTTP file upload from Java client -
i want upload file client server.
client: java using http post server: java servlet
i have added client side coding here. but, don't have idea server side processing. please me code snippet.
private string tag = "uploader"; private string urlstring = "http://192.168.42.140:8080/sampweb"; httpurlconnection conn; string exsistingfilename = "/sdcard/log.txt"; string lineend = "\r\n"; string twohyphens = "--"; string boundary = "*****"; try { // ------------------ client request log.e(tag, "inside second method"); fileinputstream fileinputstream = new fileinputstream(new file( exsistingfilename)); // 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("content-type", "multipart/form-data;boundary=" + boundary); dataoutputstream dos = new dataoutputstream(conn.getoutputstream()); dos.writebytes(twohyphens + boundary + lineend); dos .writebytes("content-disposition: post-data; name=uploadedfile;filename=" + exsistingfilename + "" + lineend); dos.writebytes(lineend); log.e(tag, "headers written"); // create buffer of maximum size int bytesavailable = fileinputstream.available(); int maxbuffersize = 1000; // int buffersize = math.min(bytesavailable, maxbuffersize); byte[] buffer = new byte[bytesavailable]; // read file , write form... int bytesread = fileinputstream.read(buffer, 0, bytesavailable); while (bytesread > 0) { dos.write(buffer, 0, bytesavailable); bytesavailable = fileinputstream.available(); bytesavailable = math.min(bytesavailable, maxbuffersize); bytesread = fileinputstream.read(buffer, 0, bytesavailable); } // send multipart form data necessary after file data... dos.writebytes(lineend); dos.writebytes(twohyphens + boundary + twohyphens + lineend); // close streams log.e(tag, "file written"); fileinputstream.close(); dos.flush(); dos.close(); } catch (malformedurlexception ex) { log.e(tag, "error: " + ex.getmessage(), ex); } catch (ioexception ioe) { log.e(tag, "error: " + ioe.getmessage(), ioe); } try { bufferedreader rd = new bufferedreader(new inputstreamreader(conn .getinputstream())); string line; while ((line = rd.readline()) != null) { log.e("dialoge box", "message: " + line); } rd.close(); } catch (ioexception ioex) { log.e("mediaplayer", "error: " + ioex.getmessage(), ioex); } }
i'm new server programming. if have done mistakes clarify me. thanks!
the best library achieve still apache commons file upload. documented , easy use. if ran issues, please check faq first.
Comments
Post a Comment