我正在尝试上传包含一些数据的图片,比如我想以键值格式发送数据:
(关键是图片) - {“image”,图片} (密钥是用户名) - {“username”,“abc @ abc.com”}
但是上传图像服务器端编码使用的是“Multipart”,任何人都可以建议我如何使用这种键值json格式以多部分格式发送图像?
这是我的申请:
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "xxxxxxxx";
String EndBoundary = "";
String str = twoHyphens + boundary + lineEnd;
String str2 = "Content-Disposition: form-data; name=\"username\"";
String str3 = "abc@abc.com";
String str4 = "Content-Disposition: form-data; name=\"imgName\"";
String str5 = "Content-Type: image/jpeg";
String str6 = twoHyphens + boundary + twoHyphens;
StrTotal = str + str2 + "\r\n" + str3 + "\r\n" + str
+ str4 + "\r\n" + str5 + "\r\n"+"\r\n"+ encodedImage + "\r\n" + str6;
这是多部分代码,现在我想将它从json格式发送到服务器。
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", "abc@abc.com"));
param.add(new BasicNameValuePair("image", ???));
这个param值对服务器,但如何用这个发送多部分数据?
答案 0 :(得分:1)
你可以做这样的事情
public void uploadUserPhoto(File image) {
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Title", new StringBody("Title"));
multipartEntity.addPart("Nick", new StringBody("Nick"));
multipartEntity.addPart("Email", new StringBody("Email"));
multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}
}