How to upload multiple images using multi-part in Volley in Android - android

I want to upload multiple images to server using multi-part, I didn't get proper code, anyone please help me to fix solve my problem.If i send as base64 format ,backend team cant able to get my image. Thats' why I go with multipart. Either Volley or Asynctask.
I tried this code from this link
https://www.simplifiedcoding.net/upload-image-to-server/
But multiple images I dont know how to do.
Main.Java
package com.getspot.getspot.imagerestapi;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
imageView.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
uploadBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
Log.i("AS","--"+byteArrayOutputStream.toByteArray());
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
//getting the tag from the edittext
final String tags = editTextTags.getText().toString().trim();
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, ServerUtils.Gs_Clock_Image,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Log.i("AS","obj--"+obj);
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("AS","error--"+error);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("gs_userId", "6");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
Log.i("AS","imagename--"+imagename);
Log.i("AS","getFileDataFromDrawable(bitmap)--"+getFileDataFromDrawable(bitmap));
params.put("gs_task_image", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
Note:While passing the byte-array in gs_text_image,in that how can i send multiple images.I referred that above link.Please help me

I'll show you how I do it (particular case ofc, but it might give you an idea)
So, first of all you need the method interface which will look like this:
#Multipart
#POST(RestClient.UPLOAD_PICTURES_FOR_ORDER)
Call<YourTypeOfResponse> uploadPictures(#Part("images[]") RequestBody[] file, #Part MultipartBody.Part[] images);
now, you will have to prepare the files(images) that you have, for the request
private void multiparts(){
RequestBody reqFullPicFile;
MultipartBody.Part filepart;
RequestBody filename;
images = new MultipartBody.Part[files.size()];
filenameImages = new RequestBody[files.size()];
for (int file = 0; file < files.size(); file++){
reqFullPicFile = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(file));
filepart = MultipartBody.Part.createFormData("full_picture", files.get(file).getName(), reqFullPicFile);
filename = RequestBody.create(MediaType.parse("text/plain"), files.get(file).getName());
images[file] = filepart;
filenameImages[file] = filename;
}
}
And, in the end, make the request with the created Multiparts (in this case images & filenameImages)
private void uploadPicturesReq(){
if (files != null) {
multiparts();
RestClient.getApi().uploadPictures(filenameImages, images)
.enqueue(new Callback<PicturesResponse>() {
#Override
public void onResponse(Call<PicturesResponse> call, Response<PicturesResponse> response) {
if (response.isSuccessful() && response.code() == 200) {
// here you can handle the response from server
}
}
#Override
public void onFailure(Call<PicturesResponse> call, Throwable t) {
Log.e(TAG, "-=onFailure=- " + t.getMessage(), t);
}
});
}
}

Related

How to handle interface for onActivityResult Override Method

I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need.
Here is my Adapter Class.
public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {
private static final String TAG = "resPoster";
private ArrayList<Poster> posterArrayList;
private Context context;
public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
this.posterArrayList = posterArrayList;
this.context = context;
}
#NonNull
#Override
public PosterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.sending_image_layout, viewGroup, false);
return new PosterViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull PosterViewHolder posterViewHolder, int i) {
posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/providers");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
Log.d(TAG,"filename: " + fileName);
File outFile = new File(dir, fileName);
Log.d(TAG,"outFile: " + outFile);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(i, 0);
((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
}
});
}
#Override
public int getItemCount() {
return posterArrayList.size();
}
public class PosterViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayoutImage;
ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
CircleImageView imageViewProfie;
public PosterViewHolder(#NonNull View posterView) {
super(posterView);
relativeLayoutImage = posterView.findViewById(R.id.image_relative);
imageViewBg = posterView.findViewById(R.id.image_bg);
imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
imageViewEdit = posterView.findViewById(R.id.edit_image);
imageViewDownload = posterView.findViewById(R.id.download_image);
imageViewShare = posterView.findViewById(R.id.share_image);
}
}
}
and I want to use this class
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
final Uri selectedUri = data.getData();
if (selectedUri != null) {
startCrop(selectedUri);
} else {
Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
Please Help me handle this method in interface.
Thank you.
**UPDATE: **
Here is my activity code to understand more my question.
RequestQueue requestQueue;
private ArrayList<Poster> posterArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private PosterAdapter posterAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sending_image);
requestQueue = Volley.newRequestQueue(this);
recyclerView = findViewById(R.id.recycler_poster);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
getAllPoster();
}
private void getAllPoster() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("poster_id", "1");
Log.d(TAG + "pp", String.valueOf(params));
String Url = Constants.Base_URL + "poster/";
JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
response -> {
Log.d("responsePending", String.valueOf(response));
try {
String statusResponseObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusResponseObject.equals("200")){
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pendingFragResponse = jsonArray.getJSONObject(i);
String posterObject = pendingFragResponse.getString("poster");
String positionObject = pendingFragResponse.getString("position");
String sizeObject = pendingFragResponse.getString("size");
String txt_positionObject = pendingFragResponse.getString("txt_position");
String titleObject = pendingFragResponse.getString("title");
String descriptionObject = pendingFragResponse.getString("description");
//
posterArrayList.add(new Poster(posterObject, positionObject,
sizeObject, txt_positionObject,
titleObject, descriptionObject));
posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
recyclerView.setAdapter(posterAdapter);
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
}
posterAdapter.notifyDataSetChanged();
// wp10ProgressBar.hideProgressBar();
}else {
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
Rather than using Interface pattern just create public method inside your adapter and call that method when your onActivityResult hits in Activity.
(This answer is just a workaround for your scenario. Ideally you should not pass your activity Context to your adapter, rather than use Interface pattern and receive callback inside your activity whenever any action took place (like clicking on edit button) inside your activity and pass relevant data while trigger callback from your adapter.)
You can refer AllNoteActivity and NoteAdapter for reference here
So what you need to do is put the current method onActivityResult() from PosterAdapter to the activity. Then make the methods startCrop(), handleCropResult() and handleCropError() public (I assume are in PosterAdapter).
In the onActivityResult() change the call of startCrop() to posterAdapter.startCrop(). Same for the other methods. And that should do it.
Create a method in adapter
In your adapter class
public void waterverYouWantMethod(){
}
And call that method from Activity when onActivityResult mehtod called.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// call that method here
adapter.wateverYouWantMethod();
}
}

Retrofit 2 image upload

in fact I am in the process of preparing an android application that makes the upload of an image on a server thanks to a REST API.
I tested lapi with POSTMAN and I have no errors.
but have an error in this part: I that the crash app before intent
this is my source codes:
public class FileShooser extends AppCompatActivity {
private static final int INTENT_REQUEST_CODE = 100;
private String name ;
private CompositeSubscription mSubscriptions;
ProgressDialog progressdialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSubscriptions = new CompositeSubscription();
// get name from last activity
name= getIntent().getStringExtra("Name");
// start file shooser intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
try {
startActivityForResult(intent, INTENT_REQUEST_CODE );
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==INTENT_REQUEST_CODE)
{
if(resultCode==RESULT_OK){
uploadImage( data.getData());
}
}
}
public byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream byteBuff = new ByteArrayOutputStream();
int buffSize = 1024;
byte[] buff = new byte[buffSize];
int len = 0;
while ((len = is.read(buff)) != -1) {
byteBuff.write(buff, 0, len);
}
return byteBuff.toByteArray();
}
private void uploadImage(Uri fileUri) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
// use the FileUtils to get the actual file by uri
File file = new File(fileUri.getPath());
showSnackBarMessage("name:"+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// progress dialog
progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please wait ...");
progressdialog.show();
retrofitInterface.upload(name,body).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError);
}
private void handleError(Throwable error) {
progressdialog.dismiss();
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("Network Error !");
}
}
private void handleResponse(Response response) {
progressdialog.dismiss();
showSnackBarMessage(response.getMessage());
}
private void showSnackBarMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
thank you very much for your answers

how can i send to server without image in volley?

this is my method to post in server with two string and one image here i van send data correctly but when i send without image no data can be sent i want to send string and image in all cases with image and without image.
private void Posts()
{
final StringRequest stringRequest=new StringRequest(Request.Method.POST, uploadeImageUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String Response=jsonObject.getString("response");
Toast.makeText(Post.this,Response,Toast.LENGTH_LONG).show();
imagepost.setImageResource(0);
imagepost.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params =new HashMap<>();
params.put("name",editwriter.getText().toString().trim());
params.put("postcontent",editsubject.getText().toString().trim());
params.put("imagepost",imageToString(bitmap).trim());
return params;
}
};
Mysingletone.getInstance(Post.this).addToRequestque(stringRequest);
}
this is the code of imagetostring with method that get image
private void selectImages(){
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMG_REQUEST);
}
private String imageToString(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgbystes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgbystes,Base64.DEFAULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==IMG_REQUEST&&resultCode==RESULT_OK&&data!=null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
imagepost.setImageBitmap(bitmap);
imagepost.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}}
code of php in server .
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con)
{
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
$image = $_POST["image"];
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
$sql2="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent')";
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql))
{
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
}
else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);
?>
Can you add the code of imageToString(Bitmap bitmap)?
Edit:
First of all add if statement to getParams() method like this:
String imageString = imageToString(bitmap);
if(!imageString.equals("false")){
params.put("imagepost",imageToString(bitmap).trim());
}
and let imageToString method return "false" as String when error.
Edit your php script like this:
$con= mysqli_connect($host_name,$user_name,$user_pass,$dp_name);
if($con){
date_default_timezone_set("Asia/Muscat");
$datee= date("Y/m/d");//strip_tags(trim($_POST["date"]));
$timee= date("h:i:sa");//strip_tags(trim($_POST["time"]));
$dt=date("Ymd");
$tm=date("his");
$name=$_POST['name'];
$postcontent=$_POST['postcontent'];
if(isset($_POST["image"])){
$imageChecker = TRUE;
$imagepost= $_POST["imagepost"];
$rnd = rand(0, 5000);
$imgname="imagepost".$dt.$tm.$rnd.".jpg";
$url = "http://devsinai.com/DrSiani/imageUploadPostDr/images/".$imgname;
$sql="INSERT INTO posts (name,postcontent,imagepost) VALUE ('$name','$postcontent','$url')";
} else {
$imageChecker = FALSE;
$sql="INSERT INTO posts (name,postcontent) VALUE ('$name','$postcontent')";
}
$uploads_path="images/$imgname";
if(mysqli_query($con,$sql)){
if($imageChecker)
file_put_contents($uploads_path,base64_decode($imagepost));
echo json_encode(array('response'=>'Successfully'));
} else {
echo json_encode(array('response'=>'fiald'));
}
}
mysqli_close($con);

upload video using Retrofit 2

I want to upload a video file using Retrofit 2, please help me doing this.
This is my endpoint:
upload.php:
<?php
$uploaddir = '../uploads/';
$uploadfile = $_FILES['userfile']['name'];
$response = array();
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir.$uploadfile))
{
$response["result"] = "1";
echo json_encode($response);
} else
{
$response["result"] = "-1";
echo json_encode($response);
}
?>
I tried to follow a sample (combining it with file selection from the gallery) on the web, but it doesn't even compile (I have marked the erroneous line by a comment):
MainActivity:
public class MainActivity extends Activity
{
private static int RESULT_LOAD_VIDEO = 1;
String decodableString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_load = (Button) findViewById(R.id.buttonLoadVideo);
btn_load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
loadVideoFromGallery(btn_load);
}
});
}
/*
* PICK THE VIDEO AND EXTRACT ITS ADDRESS
*/
public void loadVideoFromGallery(View view)
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VIDEO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
try {
// When a video is picked
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK
&& null != data)
{
// Get the video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(selectedVideo,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
decodableString = cursor.getString(columnIndex);
Log.i("mok",decodableString);
cursor.close();
upload(decodableString);
} else
{
Toast.makeText(this, "You haven't picked any video",
Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
/*
* UPLOAD THE SELECTED VIDEO TO THE SRVER
*/
public void upload(String decodableString)
{
final String BASE_URL = "http://192.168.1.7/";
Retrofit retrofit = new Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UploadApiService service = retrofit.create(UploadApiService.class);
MediaType MEDIA_TYPE = MediaType.parse("video/mp4");
File file = new File("/storage/emulated/0/Pictures/MyApp/test.png");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE, file);
Call<com.squareup.okhttp.ResponseBody> call = service.uploadVideo("desc", requestBody);
call.enqueue(new Callback<ResponseBody>(){ //error even before compile***
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit)
{
// TODO Auto-generated method stub
if (response.isSuccess())
{
Log.i("mok","S");
ResponseBody rb = response.body();
Log.i("mok",rb.getUsername());
}
else
{
Log.i("mok","F");
com.squareup.okhttp.ResponseBody rb = response.errorBody();
}
}
#Override
public void onFailure(Throwable t)
{
t.printStackTrace();
Log.i("mok",t.getCause()+"");
Log.i("mok","T");
finish();
}
});
}
}
UploadApiService:
public interface UploadApiService
{
#Multipart
#POST("api/upload.php")
Call<ResponseBody> uploadVideo(#Part("description") String description, #Part("video") RequestBody video);
}
I guess I have to use a kind of Stream to keep track of the progress but unfortunately I don't know more.
Make sure you imports are the correct. For example, Callback should be retrofit.Callback;, not import com.squareup.okhttp.Callback;. Based on your comment, it sounds like the real problem was a type conflict with a locally defined ResponseBody.

How to upload Android sqlite BLOB data into MySQL BLOB

I am developing a project where user store some information and image into SQLite database. The image is stored as BLOB data. Now I want to upload all data into my MySQL database. I am using Volley to upload all rows one by one from SQLite to MySQL server with a AsyncTask calling a Web API.
Everything working fine without the image BLOB data. I do not know is there any way to upload blob data using Volley.
I have search a lot into StackOverflow but did not get any solution, please help me.
I am giving some code example to make my question better understandable.
Here is my function calling in a AsyncTask:
/**
* function to upload data into server
* */
private void SyncTaskDoInBack(final dataDB data) {
// Tag used to cancel the request
String tag_string_req = "Inserting Online";
StringRequest strReq = new StringRequest(Method.POST, AppConfig.API_LINK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
Log.d(TAG, "Success");
} else {
// Error in found
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ID", data._id);
params.put("PersonName", data.pName);
params.put("Photo", data.photo.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
My "dataDB" Class is as follows:
public class dataDB implements Comparable<dataDB>{
String _id = null;
String pName = null;
byte[] photo = null;
#Override
public int compareTo(dataDB o) {
//return title.toLowerCase().compareTo(o.title.toLowerCase());
return 0;
}
}
List Data Model class is follows:
public class ListDataModel {
private int _id;
private String name;
private byte[] image;
public ListDataModel() { }
public ListDataModel(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
After searching a lot into StackOverflow, I have come up with the following formula, which appears to produce the camera image into Base64 String and Vice-versa. Hope this will help others.
I am using Apache Commons Codec for Base64 encode/decode from here http://commons.apache.org/proper/commons-codec/ (I think one can use Android default Base64 class too, I am using this for other purposes also)
Here is my onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap myImage = extras.getParcelable("data");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 90, bao);
imageInByte = bao.toByteArray();
imageInBase64Str = Base64.encodeBytes(imageInByte); // using internal class
}
break;
}
}
Then I'm passing the Base64 String imageInBase64Str to my insert statement of SQlite and MySQL online database.
When getting image Base64 encoded data from SQLite or MySQL to view, I'm processing my image like the following way:
try {
byte[] decodedByte = Base64.decode(imageData, 0);
theImage = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}catch (IOException io){
Log.d("ViewRecord",io.getMessage());
}
That's it :)

Categories

Resources