I am trying to send a bitmap (image captured in camera - Android) to nodejs. I am using AsycnHttpClient for the same. I am able to successfully send query parameters. I did refer to some of the links where the files are being sent and received. I tried the same, however, I guess nodejs code needs to be different for a bitmap and file (not sure?!)
Please can you help?
Client side code:
private void storeImage(Bitmap bm){
AsyncHttpClient client = new AsyncHttpClient();
//Append the parameters in the Service URL
RequestParams rp = new RequestParams();
String SERVICE_URL_REG = SERVICE_URL + "uploadImage?userID=rhari008";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
ByteArrayInputStream bInput = new ByteArrayInputStream(data);
rp.put("image",bInput);
client.post(SERVICE_URL_REG, rp, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG,"Successfully uploaded the image");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG,"Error in uploading the image");
}
});
}
Server side code to receive the parameter:
//Image upload
router.post('/uploadImage', function(req, res, next) {
console.log("Image upload reached for " + req.query.userID);
var file = req.files.image;
console.log("File received : ");
//console.log("Image path : "+req.files.image.path);
res.json({result:"success"});
});
Please make sure your NodeJS server supports multipart first.
Yes.. I was able to arrive at the solution finally. I encoded the bitmap on base64 to stringify the same. That was stored post the compression. I retrieved it based and decoded the same to bitmap. It worked.
Related
I am trying to get make a post request in Android using AsyncHttpClient using this code:
JSONObject jsonParams=new JSONObject();
try {
jsonParams.put("email", email);
}
catch (Exception e){
}
try {
StringEntity entity = new StringEntity(jsonParams.toString());
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(),URL,entity, "application/json", new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {}
});
I am trying to access this data sent in the post request in my Python server. However, whenever I do request.json in my Python server, I get 'None' as response.
I also tried request.get_json(force=True) but getting 404 error code.
I dont really know if the data is being sent by the client APP or I am making a mistake while trying to retrieve it at the server side. Please help me with this issue.
String content = new String(responseBody);
Log.e("SUCCESS_RESP",""+content);
I am trying to upload an image to a PHP file on a server using the POST method. I have been trying to do this using LoopJ AndroidAsyncHttp with no success. The server also requires a basic auth username and password. So far, I have been able to successfully POST the regular data parameters (These are simple string key-valued pairs like: "name":"joe") and get a response from the server. However, as soon as I try to attach the image to the POST request, the request fails giving me the following errors:
Error Message: null
Error Cause: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
The code that I am using follows the examples given at http://loopj.com/android-async-http/ very closely. Here is the code that I am using:
RequestParams params = new RequestParams();
params.put("name",name);
String path = "/path/to/img";
File myFile = new File(path, "picture.png");
if( myFile.exists() ) {
try {
params.put("picture", myFile);
} catch(FileNotFoundException e) {
Log.d("App","Error Attaching Picture: " + e.toString());
}
} else {
Log.d("App","File DOES NOT exist");
}
String urlString = "url-to-server";
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("User", "Pass");
client.post(urlString, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
super.onSuccess(statusCode, headers, responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
super.onFailure(statusCode, headers, responseBody, error);
Log.d("App","Upload Failed!");
Log.d("App","Error Message: " + error.getMessage());
Log.d("App", "Error Cause: " + error.getCause());
}
#Override
public void onStart() {
super.onStart();
}
});
So what am I doing wrong here?
I have also double checked and the file that I am reading to get the image does exist and it does have data in it, so I have ruled that out as a potential cause.
I have been struggling with this issue a little too long now.
Thanks in advance to anyone who can help!
This was a bug in the old 1.4.4 version of AsyncHTTPClient. It can be fixed by updating to the 1.4.8 version. In your build.gradle file under the dependencies section it should look like this:
compile 'com.loopj.android:android-async-http:1.4.8'
i'm trying to upload an image via http post method from android device to laravel server. but Posting an image is not working, the post parameter (including image file) doesn't seem to be sent correctly.
i'm using Android Asynchronous Http Client (http://loopj.com/android-async-http/) to post an image from android. and here is the code :
Android :
RequestParams params = new RequestParams();
params.put("id_personil", session.getUID());
params.put("id_deskel", session.getDID());
params.put("jenis", jenisLap.getSelectedItemPosition());
params.put("judul", judul.getText().toString());
params.put("lokasi", lokasi.getText().toString());
params.put("uraian", uraian.getText().toString());
try{
for (int a =0; a<imageUrl.size();a++){
params.put("pic[]", new File(Environment.getExternalStorageDirectory().getPath()+imageUrl.get(0)));
}
}catch(FileNotFoundException e){e.printStackTrace();}
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://10.0.3.2:8888/api/v1/lapgiat", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
ShowAlert(response.toString(), "text");
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
ShowAlert("Error", "error");
}
});
Laravel
if(Request::has('pic')){
$files = Input::file('pic');
//dd($files);
$det_pic = [];
foreach ($files as $file) {
$filename = rand(11111,99999).'.'.$file->getClientOriginalExtension();
$file->move('uploads', $filename);
$det_pic[] = ['id_lapgiat'=>$id, 'file'=>$filename];
}
DB::table('bah_det_lapgiat_photo')->insert($det_pic);
$output['has picture'] = true;
}
can anyone help me?
Check using cURL or POSTMAN client and see if it's working there. If not, you can use this sample code for laravel.
//Checks if request has file or not
if ($request->hasFile('pic')) {
//checks if file is uploaded or not
if ($request->file('pic')->isValid()) {
$extension = $request->file('pic')->getClientOriginalExtension();
$imageName = str_random(60);
$request->file('pic')->move(base_path() . 'file/save/location', $imageName.".".$extension);
}
}
I am using this code:
/* This is an asynchronusHTTP client*/
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params,new FileAsyncHttpResponseHandler(file) {
#Override
public void onSuccess(int statusCode, Header[] headers, File response) {
// Do something with the file `response`
}
});
but I got the file which is empty. Documentation says on success it writes result to the file passed but that is not happening.
What your are saying is called URL Encoding which will not give illegal character error as for as I know.. If you think that URL Encoding is the problem the try add this line in your get(String url, RequestParams params,FileAsyncHttpResponseHandler responseHandler)) function.
client.setURLEncodingEnabled(false);
I'm trying to upload a file to a django server from an android phone, and i'm getting a strange mimetype. My code utilizes the Asynchrnous HTTP request client, and I'm using the below code:
File file = new File(/*Get file*/)
RequestParams params = new RequestParams();
params.put("file", file);
getAsyncHttpClient().post(url, params, new JsonHttpResponseHandler() {
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
}
public void onSuccess(final JSONObject obj) {
Log.i(TAG, obj.toString());
}
});
The content-type I'm getting on the server from a django FileField is application/octet-stream. Is there anyway to get the real mimetype to be passed in? I have been researching on this for sometime.
I read these below links:
Uploading an image from Android (with Android Asynchronous Http Client) to rails server (with paperclip)
Android image file sent to php upload image file is application/octet-stream type and not image/jpeg?
Is there something else I should be passing into the Android Asynchronous Http Client?
Can't believe I didn't see this before.
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
You can just do:
params.put("file", file, mimetype);