Not able to upload camera captured image on server in android - android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
// I am getting onFailure executed while try to upload image from camera.
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {

As per comments :
Get image from gallery or camera like this :
File mainFile = null;
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
String partFilename = currentDateFormat();
mainFile = storeCameraPhotoInSDCard(bitmap, partFilename);
public String currentDateFormat() {
String currentTimeStamp = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
currentTimeStamp = dateFormat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return currentTimeStamp;
}
public File storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate) {
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile;
}
Use mainFile to send in RequestBody and pass like execMultipartPost(File file)

Related

How to read an image from internal storage

I have downloaded an image to my app data/data/package memory. it is downloaded, but problem is that i did not got path to display image in imageviewer. but could not. please tell me how to display. Please attention on path. thank you
Here is my download code.
ImageView imageView = (ImageView) findViewById(R.id.iv);
String mUrl = "https://cometonice.com/im.gif";
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
FileOutputStream outputStream;
String name = "im.gif";
outputStream = openFileOutput(name, Context.MODE_PRIVATE);
outputStream.write(response);
outputStream.close();
Toast.makeText(MainActivity.this, "Download complete.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
Well you can use The ImageRequest of volley like this :
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
saveBitmapToFile(bitmap)
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
and save it like :
public String saveBitmapToFile(Bitmap bitmap) {
FileOutputStream out = null;
String filename = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!f.exists()) {
f.mkdirs();
}
filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp/" + UUID.randomUUID().toString() + ".jpg";
out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return filename;
}

Download POST method's PDF response using retrofit 2

I am new to android and JSON using retrofit. I am using retrofit 2 with my project.
This is one of post API and it gives a pdf as the response.
#POST("examples/campaign_report_new.php")
Call<ResponseBody> getAddressTrackingReport(#Body ModelCredentialsAddressTracking credentials);
I used the below code to do this function and I stuck in the response method to download and show that pdf.
private void downloadPdf() {
ModelCredentialsAddressTracking
credentials = new ModelCredentialsAddressTracking(campaign,
dateFrom, dateTo);
ApiService apiService = RetroClient.getApiService();
Call<ResponseBody> call = apiService.getAddressTrackingReport(credentials);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.d(TAG, String.valueOf(response.body().bytes()));
} catch (IOException e) {
e.printStackTrace();
}
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
Below link is the response I got from Postman:
click here
writeResponseBodyToDisk() function :
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Door Tracker");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("door tracker", "Oops! Failed create "
+ "door tracker" + " directory");
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "AddressTrackingReport "+ timeStamp + ".pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(mediaFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
Somebody, please help a solution. This may contain errors Because I am new to it.Thanks.
Your API using form-data as input, So change #Body to #Multipart Type. This will give you a response. Add below snippet inside onResponse()
if (response.isSuccessful()) {
progressDialog.dismiss();
new AsyncTask<Void, Void, Void>() {
boolean writtenToDisk = false;
#Override
protected Void doInBackground(Void... voids) {
try {
writtenToDisk = writeResponseBodyToDisk(AddressTrackingActivity.this,
response.body());
} catch (IOException e) {
Log.w(TAG, "Asynch Excep : ", e);
}
Log.d(TAG, "file download was a success? " + writtenToDisk);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (writtenToDisk) {
String pdfPath = Environment.getExternalStorageDirectory().toString()
+ "/Door Tracker/" + fileName;
Log.d(TAG, "file name : " + fileName);
File file = new File(pdfPath);
Uri bmpUri;
if (Build.VERSION.SDK_INT < 24) {
bmpUri = Uri.fromFile(file);
Log.d(TAG, "bmpUri : " + bmpUri);
} else {
bmpUri = FileProvider.getUriForFile(AddressTrackingActivity.this,
getApplicationContext().getPackageName() + ".provider", file);
Log.d(TAG, "bmpUri : " + bmpUri);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(bmpUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "ActivityNotFoundException : ", e);
}
}
}
}.execute();
} else {
progressDialog.dismiss();
Toast.makeText(AddressTrackingActivity.this, "Network error, Please retry", Toast.LENGTH_SHORT).show();
Log.d(TAG, "server contact failed");
}
I think this will help you.
String fileName = "";
boolean writtenToDisk = writeResponseBodyToDisk(response.body(),fileName);
if(writtenToDisk){
String pdfPath = Environment.getExternalStorageDirectory().toString() + "/Door Tracker/"+fileName;
File file = new File(pdfPath);
Uri bmpUri;
if (Build.VERSION.SDK_INT < 24) {
bmpUri = Uri.fromFile(file);
} else {
bmpUri = FileProvider.getUriForFile(this,getApplicationContext().getPackageName() + ".provider", file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(bmpUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
}
}
Just get the File Name from method writeResponseBodyToDisk :
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "AddressTrackingReport "+ timeStamp + ".pdf");
fileName = mediaFile.getName();
Just Debug and Check your file name is correct.

Retrofit 2 download image and save to folder

I need to download image from server and save it to folder, so I am using Retrofit 2.
Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null.
I do not get why, here is my code:
#GET("images/{userId}/{imageName}")
#Streaming
Call<ResponseBody> downloadImage(#Path("userId") String userId, #Path("imageName") String imageName);
Download image code:
private void downloadImage(final int position) {
String url = "htttp://myserver.com/";
retrofitImage = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
imageApi = retrofitImage.create(BlastApiService.class);
String userId = feedList.get(position).getUserId();
String fileName = feedList.get(position).getFile();
Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
imageCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccess()){
String fileName = feedList.get(position).getFile();
InputStream is = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
saveImage1(bitmap, fileName);
} else{
try {
Log.d("TAG", "response error: "+response.errorBody().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
}
});
}
Here is method to save image.
private void saveImage1(Bitmap imageToSave, String fileName) {
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
counter++;
// if (counter < feedList.size()) {
//downloadImage(counter);
//} else {
setImage();
//}
} catch (Exception e) {
e.printStackTrace();
}
}
This worked for me:
public static boolean writeResponseBody(ResponseBody body, String path) {
try {
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
//long fileSize = body.contentLength();
//long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
//fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
after call this method you can get image from path:
boolean result = writeResponseBody(body, path);
if(result) {
Bitmap bitmap = BitmapFactory.decodeFile(path)
}
private boolean writeResponseBodyToDisk(ResponseBody body, String name) {
try {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/MyApp";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, name + ".pdf");//am saving pdf file
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

Writing and reading file

I'm having a problem writing and reading files.
Here goes the code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch(requestCode) {
case INTENT_COUNTRY:
if (data.getExtras().containsKey("country")) {
final String c = data.getStringExtra("country");
Log.d("Profile", "Country: " + c);
txtCountry.setText(c);
}
break;
case PICKER_CAMERA:
Log.d("Profile", "PICKER_CAMERA");
Bitmap bitmapCamera = (Bitmap) data.getExtras().get("data");
Bitmap thumbnailCamera = ThumbnailUtils.extractThumbnail(bitmapCamera, 320, 320);
ByteArrayOutputStream streamCamera = new ByteArrayOutputStream();
thumbnailCamera.compress(Bitmap.CompressFormat.PNG, 100, streamCamera);
byte[] byteArrayCamera = streamCamera.toByteArray();
InputStream isCamera = new ByteArrayInputStream(byteArrayCamera);
uploadPicture(isCamera);
break;
case PICKER_GALLERY:
Log.d("Profile", "PICKER_GALLERY");
Uri imageUri = data.getData();
try {
Bitmap bitmapGallery = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
Bitmap thumbnailGallery = ThumbnailUtils.extractThumbnail(bitmapGallery, 320, 320);
ByteArrayOutputStream streamGallery = new ByteArrayOutputStream();
thumbnailGallery.compress(Bitmap.CompressFormat.PNG, 100, streamGallery);
byte[] byteArrayGallery = streamGallery.toByteArray();
InputStream isGallery = new ByteArrayInputStream(byteArrayGallery);
uploadPicture(isGallery);
} catch(IOException e) {
e.printStackTrace();
}
break;
default:
Log.d("Profile", "Unmanaged request code: " + requestCode);
break;
}
}
}
public void uploadPicture(InputStream is) {
final ProgressDialog progress = new ProgressDialog(getActivity());
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setTitle(getString(R.string.loading));
progress.setMessage(getString(R.string.loading_msg));
progress.show();
/* Upload*/
AppDelegate appDelegate = (AppDelegate) getActivity().getApplication();
appDelegate.setPicture(is, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload ok");
progress.dismiss();
return null;
}
}, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload failed");
progress.dismiss();
return null;
}
});
}
public void setPictureFile(final InputStream is) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(IOUtils.toByteArray(is));
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
BufferedInputStream buf = new BufferedInputStream(inputStream);
bitmap = BitmapFactory.decodeStream(buf);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
if (inputStream != null) {
inputStream.close();
}
if (buf != null) {
buf.close();
}
} catch(FileNotFoundException e) {
Log.d("Profile", "Picture FILE not found.");
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
Log.d("Profile", "Out Of Memory");
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
In console I always have:
WARNING: bitmap == null
The InputStream in the setPictureFile method is not null (upload to a web-services works as expected) and I didn't get any exception in setPictureFile.
On the other hand, when I'm trying to read the file, the bitmap seems to be null, no exception is rising up!
The file I'm trying to read is about 200-300 KB, so it's not big, I'm not running out of memory.
Anyone knows what's going on?
Solved. Using byte[] instead of InputStream everywhere, solved my issue.
public void setPictureFile(final byte[] buffer) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(buffer);
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
Log.d("Profile", e.toString());
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
// http://stackoverflow.com/questions/11182714/bitmapfactory-example
// http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
byte[] reader = new byte[inputStream.available()];
if (inputStream.read(reader)!=-1) {
Log.d("Profile", "Reading from stream...");
}
Log.d("Profile", "Stream length: " + reader.length);
bitmap = BitmapFactory.decodeByteArray(reader, 0, reader.length);
//BufferedInputStream buf = new BufferedInputStream(inputStream);
//bitmap = BitmapFactory.decodeStream(inputStream);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
inputStream.close();
//if (buf != null) {
// buf.close();
//}
} catch(FileNotFoundException e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
} catch (OutOfMemoryError e) {
Log.d("Profile Exception", e.toString());
} catch(Exception e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
}
return bitmap;
}

okhttp multipart image upload with file name

i am trying to upload a image to server from an android phone. this is what i have done so far
OkHttpClient client = new OkHttpClient();
MultipartBuilder builder = new MultipartBuilder();
builder.type(MultipartBuilder.FORM).addPart(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestPackage.getJsonParam().toString()));
for (int i = 0; i < requestPackage.getPics().size(); i++) {
builder.addPart(RequestBody.create(MediaType.parse("image/png"/* + i*/), new File(URI.create(requestPackage.getPics().get(i)))));
Log.i("image to upload",URI.create(requestPackage.getPics().get(i)).toString());
}
requestBody = builder.build();
Request request = new Request.Builder().url(requestPackage.getUri()).post(requestBody).build();
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// System.out.println(response.body().string());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
how do i add names to the different parts.because if there is no name(key) to them then how will server side guy store it?
Get OkHttp 2.1, and use MultipartBuilder.addFormDataPart() which takes the filename as a parameter.
The syntax seems to have changed a bit since the previous answers. I'm using OkHttp 3.2.0.
public void upload(String url, File file) throws IOException {
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("image/png"), file))
.addFormDataPart("other_field", "other_field_value")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = this.client.newCall(request).execute();
}
You can find all in the official document: https://github.com/square/okhttp/wiki/Recipes
Especially you will be interested in folowing piece from Posting a multipart request:
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Here is a complete solution, of how to upload a file using okhttp3.
Firstly, add a file picker with a button on click listener to your code like this:
A button to pick file:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_choose_file:
showFileChooser();
break;
}
}
private String filePath = null;
private File sourceFile;
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
Then handle onActivityResult like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
File file = new File(getCacheDir(), getFileName(uri));
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Log.e("InputStream Size","Size " + inputStream);
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size","Size " + file.length());
inputStream.close();
outputStream.close();
file.getPath();
Log.e("File Path","Path " + file.getPath());
file.length();
Log.e("File Size","Size " + file.length());
if(file.length() > 0){
sourceFile = file;
filePath = sourceFile.getPath();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
} else {
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private String getMimeType(String path) {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
Finally, handle the file upload along with other needed information like this :
try {
UpdateInformation("yourEmailAddress", filePath, sourceFile);
} catch (IOException e) {
e.printStackTrace();
}
private void UploadInformation(String email, final String _filePath, final File file) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
//show progress bar here
}
});
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
String mime = getMimeType(_filePath);
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse(mime), file))
.addFormDataPart("email", email)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("yourEndPointURL")
.post(body)
.addHeader("authorization", "yourEndPointToken")
.addHeader("content-type", "application/json")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
//hide progress bar here
}
});
}
#Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
final String myResponse = response.body().string();
runOnUiThread(new Runnable() {
#Override
public void run() {
//hide progress bar here
//Cont from here
//Handle yourEndPoint Response.
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Note: Don't forget to add this permission to the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can use multipart like below to send multiple values in single request
HttpPost httppost = new HttpPost(mPostURL);
MultipartEntity entity = new MultipartEntity();
entity.addPart("value", new StringBody("upload", Charset.forName("UTF-8")));
File myFile = new File(mFilePath);
FileBody fileBody = new FileBody(filePath);
entity.addPart("file", fileBody);
entity.addPart("filename", new StringBody("fileName", Charset.forName("UTF-8")));
httppost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();

Categories

Resources