Skip to content

Instantly share code, notes, and snippets.

@gvsharma
Created June 5, 2014 05:16
Show Gist options
  • Save gvsharma/d580117c438cf5761259 to your computer and use it in GitHub Desktop.
Save gvsharma/d580117c438cf5761259 to your computer and use it in GitHub Desktop.
upload an image to server(provided webservice) using POST,
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public File createTempFile(String filePath) {
File tempFile = null;
try {
Bitmap bitmap = decodeSampledBitmapFromPath(filePath, desiredImageWidth, desiredImageHeight);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
tempFile = new File(getExternalCacheDir() + File.separator + new Date().getTime() + ".jpg");
tempFile.createNewFile();
Log.d("", "get temp file path: " + tempFile.getAbsolutePath());
//write the bytes in file
FileOutputStream fo = new FileOutputStream(tempFile);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
return tempFile;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
sourceFileUri --> is the savedImagePath
upLoadServerUri --> id th URL to which we have toi post image
public int uploadFile(String sourceFileUri, String upLoadServerUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
File tempFile = null;
if (sourceFileUri != null) {
tempFile = createTempFile(sourceFileUri);
}else {
tempFile = createTempFileWithNoImage(sourceFileUri);
}
try {
FileInputStream fileInputStream = new FileInputStream(tempFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("profile_pic", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"profile_pic\";filename=\""+ tempFile.getPath() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.d("", "bytesRead :" + bytesRead);
Log.d("", "bytesRead : bufferSize: " + 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);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage+ ": " + serverResponseCode);
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
ex.printStackTrace();
Toast.makeText(LoginActivity.this,"MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
e.printStackTrace();
Toast.makeText(LoginActivity.this,"Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
tempFile.delete();
}
return serverResponseCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment