I'm trying to implement a function, which passes base64 encoded image from a webview to my web application via HTTP Post. And then, lets say, this image must be shown right away in my view. I've used this example but it didn't work properly, so after googling a little bit, I've started using AsyncTask:
public void tryUpload(String url, Context context) {
new UploadTask(context).execute(url);
}
private class UploadTask extends AsyncTask<String, Void, HttpResponse> {
private Context context;
public UploadTask(Context ctx) {
context = ctx;
}
@Override
protected HttpResponse doInBackground(String... urls) {
List<NameValuePair> formData = new ArrayList<NameValuePair>(3);
formData.add(new BasicNameValuePair("image", "base64EncodedString"));
HttpPost httpPost = new HttpPost(urls[0]);
try {
httpPost.setEntity(new UrlEncodedFormEntity(formData, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
WebView browser = (WebView) findViewById(R.id.my_web_engine);
browser.setWebChromeClient(new MyWebChromeClient());
browser.setWebViewClient(new MyWebViewClient());
try{
String data = new BasicResponseHandler().handleResponse(response);
browser.loadDataWithBaseURL(urls[0], data, "text/html", HTTP.UTF_8, null);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
if (responseBody.equalsIgnoreCase("OK"))
Log.w("myApp", "Everything is OK");
else
Log.w("myApp", "Something is wrong");
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Intent.ACTION_SEND.equals(action) && type != null) {
if (type.startsWith("image/")) {
// for simplicity skipped image encoding to base64
String url = getResources().getString(R.string.url) + "/MyController/ImageUpload";
Context context = ImageUploadActivity.this;
tryUpload(url, context);
}
}
}
}
And here is my ASP.NET MVC action:
// temporary removed authorization
[HttpPost]
public ActionResult ImageUpload(string image)
{
// skipped some lines
ViewData.Add("imageFromWebView", image);
return View();
}
And a View
contains following line:
<img src="data:image/png;base64,<%: (string)ViewData["imageFromWebView"] %>"/>
When I delete [HttpPost]
, the view is loaded without a problem, but the image is not displayed.
But when I leave [HttpPost]
, I get an exception
org.apache.http.client.HttpResponseException: Not Found
in the following line:
String data = new BasicResponseHandler().handleResponse(response);
Does anyone know what I'm doing wrong?