3

这是我编写的代码,用于将二进制文件与一些字符串一起发送到 PHP Web 应用程序服务器。

public void doRegister(final String userEmail, final String userPass, final File userPhotoId) {
    HttpClient myHttpClient = new DefaultHttpClient();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HttpPost registerTry = new HttpPost(Constants.oAuthRegURL);
                MultipartEntity signupEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                signupEntity.addPart("email", new StringBody(userEmail, Charset.forName("UTF-8")));
                signupEntity.addPart("password", new StringBody(userPass, Charset.forName("UTF-8")));
                signupEntity.addPart("User[profilePicture]", new FileBody(userPhotoId, "image/jpeg"));
                registerTry.setEntity(signupEntity);
                HttpResponse signupHttpResp = myHttpClient.execute(registerTry);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

文件userPhotoId是通过相机 API 创建和返回的照片文件(我在 onActivityResult 中获取通过相机返回的数据并从中创建位图,然后从该位图创建文件对象等)

所以这里的问题是,照片​​不是以这种方式发送到服务器的。但是,如果我像这样删除FileBody部分中的mimetype :

signupEntity.addPart("User[profilePicture]", new FileBody(userPhotoId));

二进制文件/照片已正确发送。但由于 Web 应用程序需要安全性来检查传入文件以防止二进制恶意软件,我需要为实体设置 mimeType。所以谁能告诉我为什么当我在实体请求中使用 mimeType 时没有发送文件?

ps 我已经在我的项目库中导入了 httpclient-4.3.2 、 httpmime-4.3.2 、 httpcore-4.3.1 并使用 SDK 19 进行编译。

4

1 回答 1

5

好吧,我只是想通了;在 MultipartEntityBuilder 中编写了整个内容;所以关于发送二进制照片的行将是:

signupEntity.addBinaryBody("User[profilePicture]", userPhotoId, ContentType.create("image/jpeg"), ".profile.jpg");
于 2014-01-30T20:11:46.787 回答