I know this is a recurring question. There are many similar questions in the stack overflow, but I ask this question because I donβt understand how I can send some data using Image.
I want to transfer the first and last name with the image to the server. I have still tried this.
URL connectURL; connectURL = new URL("some URL"); File sdImageMainDirectory = new File("/sdcard"); String existingFileName = sdImageMainDirectory.toString() +"/image.jpg"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; String Tag="3rd"; try { HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); 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: form-data; name=\"firstname\"" + lineEnd); dos.writeBytes("Dharmendra"); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"lastname\"" + lineEnd); dos.writeBytes("Patel"); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); int bytesAvailable = fileInputStream.available(); int maxBufferSize = 1024; int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int 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); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 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); }
source share