我正在尝试将照片从Android设备上传到php网站。
为此,我使用MultipartEntity
编码。
对于added
external jar file
我的项目我httpmime-4.1-beta1.jar
。
我要上传到php网站的内容是image
上存储的SDcard
。
为此,我在我的代码中执行以下操作:
HttpPost httppost = new HttpPost("....the link to the webiste...");
MultipartEntity reqEntity = new MultipartEntity();
StringBody sb=new StringBody("....");
File file=new File("/sdcard/image.jpg");
FileBody bin = new FileBody(file);
reqEntity.addPart("android",bin);
reqEntity.addPart("id", sb);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String page = EntityUtils.toString(resEntity);
System.out.println("PAGE :" + page);
}
但问题是来自php服务器的响应始终是一个断开的链接。
我接下来要尝试的是使用
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
但不幸的是,我导入的jar
没有HttpMultipartMode.BROWSER_COMPATIBLE
的类。所以如果你能指出我正确的方向,我真的很感激 - 我还应该为此工作输入什么....或者我应该如何将图像上传到服务器。
我必须说服务器是以这种方式上传照片的构建:
method="post" enctype="multipart/form-data"
name="form" target="_self" id="form">
<input type="hidden" name="p" value="a" />
谢谢!
答案 0 :(得分:2)
我建议不要使用beta
库。您应该使用apache-mime4j-0.6。
您还需要httpmime-4.0.1。
这些必须是你的进口:
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;