gpt4 book ai didi

Android通过http post上传多个文件到服务器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:08:18 34 4
gpt4 key购买 nike

我需要通过 HTTP POST 将文件从 Android 客户端上传到 URL。如果只上传 1 个文件,对我来说就可以了。但我的目标 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 同时上传 2 个文件?

最佳答案

我尝试了以下代码并确认这是可行的解决方案:

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作为工程库。

关于Android通过http post上传多个文件到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728689/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com