2

I'm uploading an image from my android to my web server. My web server is written in ASP.NET MVC.

I can upload my image with a HttpPost on the android and then using the following php code:

$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('App_Data/Image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);

My question is, is it possible to convert this over to my ASP.NET MVC? I feel very limited using the php as I'm not sure how to do a number of things I would be able to do in ASP.NET.

I understand the Request method in ASP.NET but I'm unsure how to do the base64_decode part.

PS. For more information on the method used, see this link

Edit: Code for the android part

This part converts the bitmap and base64 encodes it

Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/saved_images/2013-04-10--11-51-33-AEST--Fingerprint.jpg");          
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
            byte [] byte_arr = stream.toByteArray();
            String image_str = Base64.encodeBytes(byte_arr);
            ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",image_str));

This part does the post

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://myipaddress/Up/Upload");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
Mortalus
  • 10,574
  • 11
  • 67
  • 117
benallansmith
  • 816
  • 3
  • 10
  • 26
  • 1
    are you asking on how to upload a file or displaying a file ? – Mortalus Apr 17 '13 at 03:55
  • I can upload the file, but I have to put a php file in my ASPNET MVC root folder, I was wondering if it were possible to port this php code into ASP.NET – benallansmith Apr 17 '13 at 04:33
  • 1
    This file writes an image to a file .. is that what you want ? if you have uploaded the file why would you want to save it again. – Mortalus Apr 17 '13 at 04:52
  • The **android application** takes an image and base64 encodes it and then does a HttpPost. The **php** code shown above is what does the request for the image and saves it to the server, which is what I want, but I want to be able to do it in **C#** on my **asp.net** application. All the guides I have tried for uploading from **android** to **ASP.NET** don't work and the only working one I have found is this one which uses **php**. – benallansmith Apr 17 '13 at 05:32
  • 1
    See my answer it has no difference whether you access it from your web browser or android device. – Mortalus Apr 17 '13 at 07:21

2 Answers2

1

It is surprisingly simple to upload a file in MVC just use this example:

FORM:

<form action="controller\UploadImage" method="post" enctype="multipart/form-data">

  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>

Don't forget enctype="multipart/form-data" to enable file encoding.

and then in your controller do this:

[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");
}

Edit: Based on the following blog post: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/

To be able to upload files from an Android application and use the Multipart content type you need to add some additional jar files to your application.

The files needed are apache-mime4j, httpclient, httpcore and httpmime. All are opensource projects built by the Apache foundation.

Download the 4 files and add them to your project then you should be able to use the following code to post strings and files to pages.

Here is the code example:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write");


try {
  MultipartEntity entity = new MultipartEntity();

  entity.addPart("type", new StringBody("photo"));
  entity.addPart("data", new FileBody(image));
  httppost.setEntity(entity);
  HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

The image variable in this case is a File that contains an image captured by the camera on the phone.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mortalus
  • 10,574
  • 11
  • 67
  • 117
  • Thanks for the reply - although I am aware of how to do this but this is just uploading from within MVC. I'm uploading from an android app to my MVC server. (An android tag was in the topic but someone edited it out...) If I set up my controller in this way, and point the HttpPost from the android to the controller it doesn't recognize it. What I have been able to do is put the php code posted above in my root directory and point my HttpPost to that and it works but it limits me to what I'm able to do ie. I wish to use model variables in the file name/folder dir etc. – benallansmith Apr 17 '13 at 23:18
  • 1
    There is no reason that a post request will not work to the `controller\UploadImage` URL even if it comes from your android device, can you add some logs and show us what is happening there is an error probably somewhere, you do not have to use php to do this. – Mortalus Apr 18 '13 at 02:20
  • I'm not sure how to properly debug it. I have a controller action almost identical to yours outlined above. The android code for the post is `HttpPost("http:///Up/Upload");` is this correct? I have a try/catch which is successful and does `System.out.println("Post successful." + the_string_response);` which returns _post successful_ and then displays the html code for my index (since `return RedirectToAction("Index");`). I know it works since I could upload using the php code so either the MVC controller action doesn't work or I'm pointing it to the wrong address? – benallansmith Apr 18 '13 at 05:04
  • 1
    Place a breakpoint in your controller code VS and run it in debug while you post from your android device. (yes its a bit tricky). i suspect that the file is received as null. – Mortalus Apr 18 '13 at 06:31
  • so the problem is with your android app that does not post using encruption 'multipart/form-data' please add the android code that posts the file. – Mortalus Apr 18 '13 at 07:00
  • The code for the android part has been added to my original post, perhaps I need to use MultipartEntity? – benallansmith Apr 18 '13 at 23:06
1

So because I was using the base64 encoding method it wasn't working. Had to change my plan of attack and used the MultipartEntity method shown in this answer.

Also had to download apache-mime4j, httpclient, httpcore and httpmime. It is now working :-)

Thanks for your help Mortalus.

Community
  • 1
  • 1
benallansmith
  • 816
  • 3
  • 10
  • 26