Simple file uploading in android
Hey guys,
In this blog i will give you a code snippet which might come handi in file uploading
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConnection; import java.net.URL; public class DoFileUplaod { public DoFileUplaod(String FtoSave, String urlServer,String tag) { System.out.println("doupload" + FtoSave); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = FtoSave; System.out.println("url-----" + urlServer); String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { System.out.println("onee"); FileInputStream fileInputStream = new FileInputStream(new File( pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); System.out.println("two"); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); System.out.println("three"); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); System.out.println("four"); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream .writeBytes("Content-Disposition: form-data; name=\"" + tag +"\";filename=\"" + pathToOurFile + "\"" + lineEnd); outputStream.writeBytes(lineEnd); System.out.println("five"); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { System.out.println("six"); 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); System.out.println("seven"); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); System.out.println("test -----" + serverResponseCode); System.out.println("test-----" + serverResponseMessage); fileInputStream.close(); outputStream.flush(); outputStream.close(); } catch (Exception ex) { // Exception handling System.out.println("Exception" + ex); } } }And thats it simply call the function by creating the class object with the file name and server url for file uploading ...
Comments
Post a Comment