Android java code to upload file to wordpress site from app

Following example Android java code is designed to upload image file to wordpress site from android app using fileinputstream and HttpURLConnection by setting requestproperty as "Content-Type", "multipart/form-data;boundary="

FileInputStream fileInputStream = new FileInputStream(new File(filePathimg1)); URL url1 = new URL(urlServer); HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection(); // Allow Inputs & Outputs. connection1.setDoInput(true); connection1.setDoOutput(true); connection1.setUseCaches(false); // Set HTTP method to POST. connection1.setRequestMethod("POST"); connection1.setRequestProperty("Connection", "Keep-Alive"); connection1.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection1.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\";postid=\"" + postidstr + "\"" + lineEnd); outputStream.writeBytes(lineEnd); //outputStream.writeBytes("Content-Disposition: form-data; name=\"postid\"" + lineEnd); //outputStream.writeBytes(lineEnd); //outputStream.writeBytes(postidstr); // mobile_no is String variable //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 from the server (code and message) serverResponseCode = connection1.getResponseCode(); serverResponseMessage = connection1.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close(); connection1.disconnect();
Sign In or Register to comment.