Reputation: 181
I am a neophyte to android.since last couple of days I am facing some problem to send my image to server. I simply have a form that include some textfields and image to be taken from library.Everything is working perfect except image upload.I tried most of tutorials on google.The main problem is logcat is not showing any error.I am unable to track what actually went wrong. This is what I did
I used this code to get Image from galary
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
schoolLogoUpload.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I wrote this function to send selected image to server
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
This is my code to receive my image data at server side
if(Input::hasFile('image')) {
$file = Input::file('image');
$destination_path = "uploads";
$extension = Input::file('image')->getClientOriginalExtension();
$file_name = str_random(20). "." . $extension;
Input::file('image')->move($destination_path, $file_name);
}else{
return \Response::json([
"error"=>["message"=>"Please select the college logo"]
], 404);
Upvotes: 1
Views: 882
Reputation: 507
I am assuming you have converted an image to Base64
format. Basically Base64
format converts an image (or encodes an image) to the String
format.
* Write an Asynctask
that will upload an image to the server for you *
Below is the Asynctask
:-
private class AsyncUploadToServer extends AsyncTask<String, Void, String>
{
ProgressDialog pdUpload;
String imageData = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
pdUpload = new ProgressDialog(MainActivity.this);
pdUpload.setMessage("Uploading...");
pdUpload.show();
}
@Override
protected String doInBackground(String... params)
{
imageData = params[0];
HttpClient httpclient = new DefaultHttpClient();
// URL where data to be uploaded
HttpPost httppost = new HttpPost(YOUR_URL_HERE);
try
{
// adding data
List<NameValuePair> dataToBeAdd = new ArrayList<>();
dataToBeAdd.add(new BasicNameValuePair("uploadedImage", imageData));
httppost.setEntity(new UrlEncodedFormEntity(dataToBeAdd));
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.i("MainActivity", "Response: " + response);
}
catch (ClientProtocolException ex)
{
ex.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pdUpload.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully..!!", Toast.LENGTH_SHORT).show();
}
}
Hope this will help you. :-)
P.S.:- If you don't know much about asynctask, here is the link https://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 1