我有这个表格用于使用 HttpPost 将图像上传到服务器。我是使用 HTML 表单完成的,但它不适用于 Android 的 HttpPost。它响应:“您没有选择要上传的文件”。似乎文件字段尚未发送。
<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;
}
}
}
.....................
更新解决方案(它适用于我的代码)。请记住将“httpmime-4.2.1.jar”添加到您的构建路径。
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();
}
}