Android通过HTTP POST上传多个文件到服务器

4

我需要通过HTTP POST从Android客户端上传文件到URL。如果只上传一个文件,那对我来说就没问题了。但我的目标URL页面代码看起来像下面这样:

<form action="file_upload.php" enctype ="multipart/form-data" method="post">
<input type="file" name="uploadedfile">
<input type="file" name="uploadedfile2">
<input type="submit">
</form>

我该如何通过HTTP POST同时上传两个以上的文件?
1个回答

3

我尝试了以下代码并确认它可以解决问题:

StringBuffer responseBody=new StringBuffer();

Log.i(Constants.TAG, "Ready to upload file...");
HttpClient client=new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

Log.i(Constants.TAG, "Set remote URL...");
HttpPost post=new HttpPost("http://IP.IP.IP.IP/file_upload.php");
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

Log.i(Constants.TAG, "Adding file(s)...");
entity.addPart("uploadedfile", new FileBody((FileObj), "application/zip"));
entity.addPart("uploadedfile2", new FileBody((FileObj), "application/zip"));

Log.i(Constants.TAG, "Set entity...");
post.setEntity(entity);

BufferedReader bs=null;
try
{
  Log.i(Constants.TAG, "Upload...");
  HttpEntity hEntity=client.execute(post).getEntity();
  bs=new BufferedReader(new InputStreamReader(hEntity.getContent()));
  Log.i(Constants.TAG, "Response length - "+hEntity.getContentLength());
  String s="";
  while(s!=null)
  {
    responseBody.append(s);
    s=bs.readLine();
    Log.i(Constants.TAG, "Response body - "+s);
  }
  bs.close();
}
catch(IOException ioe)
{
  Log.i(Constants.TAG, "Error on getting response from Server, "+ioe.toString());
  ioe.printStackTrace();
  responseBody.append("...");
}

我的平台是Android 2.2,使用这个解决方案需要将httpmime.jar作为项目库。


如果您需要在请求中添加任何参数,则可以将其添加到MultiPartEntity对象中,例如<br> multiPartEntity.addPart("testpara,", new StringBody("value"));<br> - AnkitRox
@AnkitRox 兄弟,告诉我一些东西!你在哪里学到了 Java 中的 <br> 语法? - DiLDoST

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接