1

*Hi all, I've tried file upload to .net server using c#. Im just using the c:/inetpub/wwwroot as the server location.

My java code is,

 public class MainActivity extends Activity {
    InputStream inputStream;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.two);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.PNG,90, stream);
        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));

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://127.0.0.1/AndroidUpload/uploadImage.cs");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);
            String the_response_string = convertResponseToString(response);


            Toast.makeText(this, "Response"+the_response_string, Toast.LENGTH_SHORT).show();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this,"Error1", Toast.LENGTH_SHORT).show();
        } catch (ClientProtocolException e) {
             //TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this,"Error2", Toast.LENGTH_SHORT).show();}
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(this,"Error3", Toast.LENGTH_SHORT).show();
        }

    }
    public String convertResponseToString(HttpResponse response)throws IllegalStateException,IOException {
        // TODO Auto-generated method stub

        String res = "";
        StringBuffer buffer = new StringBuffer();
        inputStream = response.getEntity().getContent();
        int contentLength = (int) response.getEntity().getContentLength();
        Toast.makeText(this, "ContentLength"+contentLength, Toast.LENGTH_SHORT).show();

        if(contentLength<0){
                    }
        else{
            byte[] data = new byte[512];
            int len = 0;

            try {
                while(-1 != (len=inputStream.read(data))){
                    buffer.append(new String(data,0,len));
                }

                inputStream.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            res = buffer.toString();

            Toast.makeText(this, "Result"+res, Toast.LENGTH_SHORT).show();
        }

        return res;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

And my c# code for uploading is,

 protected void Page_Init(object sender, EventArgs e)
{
  string vTitle = "";
  string vDesc = "";
  string FilePath = Server.MapPath("/files/two.png");        
  if (!string.IsNullOrEmpty(Request.Form["title"]))
  {
    vTitle = Request.Form["title"];
  }
  if (!string.IsNullOrEmpty(Request.Form["description"]))
  {
    vDesc = Request.Form["description"];
  }

  HttpFileCollection MyFileCollection = Request.Files;
  if (MyFileCollection.Count > 0)
  {
    // Save the File
    MyFileCollection[0].SaveAs(FilePath);
  }
}

When Run, it throws IOException. And the file is not uploaded into that folder. Tried php code too with same result. Where is the problem?

VijayaRagavan
  • 221
  • 2
  • 15
  • Please show the IOException (stacktrace). – home Jul 12 '13 at 05:32
  • 07-12 11:59:08.594: W/System.err(491): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused W/System.err(491): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection (DefaultClientConnectionOperator.java:178) W/System.err(491): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) W/System.err(491): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) W/System.err(491): at java.net.Socket.connect(Socket.java:1055) – VijayaRagavan Jul 12 '13 at 06:38
  • 1
    And some more. All of them are warnings and no error shown. – VijayaRagavan Jul 12 '13 at 06:39

2 Answers2

1

This is a common problem. In fact you should host your asp.net web app in an iis web server (at your computer) and get your computer ip address (by ipconfig command in cmd), then put your ip address instead of "http://127.0.0.1/AndroidUpload/...". It could be like "http://192.168.1.2/AndroidUpload/..."

Android emulator cant understand 127.0.0.1 (localaddress)

Edited:

I dont how to upoad files with asp.net web forms, but If I were you I would write a simple asp.net mvc application and in a controller, I declare a action like this:

[HttpPost]
        public ActionResult UploadItem()
        {
            var httpPostedFileBase = Request.Files[0];
            if (httpPostedFileBase != null && httpPostedFileBase.ContentLength != 0)
            {
                //save file in server and return a string 
        return Content("Ok");
            }
            else
            {
               return Content("Failed")
            }
    }
Babak Fakhriloo
  • 2,076
  • 4
  • 44
  • 80
1

To connect from your emulator to your PC web-server, you need to follow the addressing convention currently used by Android. To be more specific, 10.0.2.2 is the address you want to use.

Also make sure that your AndroidManifest.xml contains the permission for Internet usage. Cheers

Trogvar
  • 856
  • 6
  • 17
  • 1
    It works without error on using ip 10.0.2.2. But the file doesn't come to the subjected folder. – VijayaRagavan Jul 12 '13 at 07:27
  • 1
    You might want to save to `string FilePath = Server.MapPath("~/files/two.png");` - notice the **~**. For a better explanation, you can look here: http://stackoverflow.com/questions/275781/server-mappath-server-mappath-server-mappath-server-mappath – Trogvar Jul 12 '13 at 07:45
  • 1
    I need to convey that i don't deal with iis or something. I just have these codes and the folder in c:/inetpub/wwwroot. Is there anything more that i need to do at this stage? – VijayaRagavan Jul 12 '13 at 08:45