android - 使用 "key-value"格式的 multipart 将图像上传到服务器

标签 android json multipartform-data

我正在尝试上传包含一些数据的图像,例如我想以键值格式发送数据:

(关键是图像)- {“图像”,图像} (关键是用户名)- {"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", ???));

并将此参数值发送给服务器,但如何发送多部分数据呢?

最佳答案

你可以这样做

    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);
    }
}

关于android - 使用 "key-value"格式的 multipart 将图像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35697888/

相关文章:

amazon-web-services - s3 预签名 url 多部分表单数据上传错误 :signature does not match

android - 在 Android 中设置按钮的 `OnClickListener` 的不同方法

json - Spring MVC - HttpMediaTypeNotAcceptableException

json - 在 Postgres 中查询 JSON

python - JSON - 使用 numpy 数组条目序列化 pandas 数据框

java - jetty 8多部分/表单数据请求

java - getSupportFragmentManager() 在我的适配器类中不起作用?

android - 如何将 Facebook 注销按钮放在导航 View 的末尾

android - AsyncTask 没有零参数构造函数

Python 请求多部分 HTTP POST