Как разместить изображение в Android

У меня есть эта форма для загрузки изображений на сервер с помощью HttpPost. Я сделал это с помощью HTML-формы, но он не работает с HttpPost для Android. Он отвечает: «Вы не выбрали файл для загрузки». Похоже, что поле файла не было отправлено.

<html>
<head>
<title>Upload Form</title>
</head>
<body>


<form action="http://192.168.0.151/index.php/upload/uploadFile" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

Код клиента

    final HttpClient client = new DefaultHttpClient();
    final HttpPost post = new HttpPost("http://" + hostName + "/upload/uploadFile");
    post.addHeader("enctype", "multipart/form-data");

    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("userfile", "/mnt/sdcard/Download/Photos/icecream.png"));

    try {
        final HttpEntity request = new UrlEncodedFormEntity(nameValuePairs);            
        post.setEntity(request);            

        final HttpResponse response = client.execute(post);

        // Get response body.
        final String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("RESPONSE BODY: " + responseBody);

    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (final ClientProtocolException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }

Класс контроллера

class Upload extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    public function showForm() {
        $this->load->view('upload_form');
    }

    public function uploadFile() {
        // Header for xml outputing.
        header('Content-type: text/xml; charset=utf-8');

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width']  = '2048';
        $config['max_height']  = '2048';

        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload())
        {
            // Get error message.
            $error = $this->upload->display_errors();

            // Prepare template.
            $xmlData = file_get_contents(TEMPLATE_XML_DIR . "upload_result.xml");
            $xmlData = str_replace("{IS_SUCCESSFUL}", 0, $xmlData);
            $xmlData = str_replace("{ERROR}", $error, $xmlData);
            echo $xmlData;
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            // Prepare template.
            $xmlData = file_get_contents(TEMPLATE_XML_DIR . "upload_result.xml");
            $xmlData = str_replace("{IS_SUCCESSFUL}", 1, $xmlData);
            $xmlData = str_replace("{ERROR}", "", $xmlData);
            echo $xmlData;
        }
    }
}

.................

Update solution (it works for my code). Remember to add "httpmime-4.2.1.jar" to your Build Path.

public void post(final String url, final List<NameValuePair> nameValuePairs) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);

    try {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for(int index=0; index < nameValuePairs.size(); index++) {
            if(nameValuePairs.get(index).getName().equalsIgnoreCase("userfile")) {
                // If the key equals to "userfile", we use FileBody to transfer the data
                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        final HttpResponse response = httpClient.execute(httpPost, localContext);

        final String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("RESPONSE BODY: " + responseBody);
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

Ответы на вопрос(1)

Ваш ответ на вопрос