如何在android中使用多部分表单数据上传文件

时间:2014-04-14 12:12:59

标签: android web-services rest multipartform-data multipartentity

如何使用多部分表单数据(@FormDataParamdata)在android中上传文件。我试图从Android端上传多个表单数据的图像文件。

Here the server script what i found at the server side:
public Image upload(@FormDataParam("image") InputStream istream,
            @FormDataParam("image") FormDataBodyPart body,
            @FormDataParam("eventId") long eventId,
            @FormDataParam("eventDescription") String eventDescription)
            throws ImageWebServiceException {
//
......
}

Here the client code what i tried for uploading in android...

Client client = new Client();
client.addFilter(new HTTPBasicAuthFilter("user123", "******"));
WebResource webResource = client.resource(url);
ClientResponse response;
FormDataMultiPart form = new FormDataMultiPart();
File file = new File("f:/android.png");
form.field("eventId", "1");
form.field("eventDescription", "password");
form.field("image", file.getName());
form.bodyPart(new FileDataBodyPart("image", file, MediaType.valueOf("image/png")));
response  = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);

For the above code im getting the 415 status code error unsupported media type.


Thanks.

1 个答案:

答案 0 :(得分:0)

 Try this
 HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (int index = 0; index < nameValuePairs.size(); index++) 
        {
            entity.addPart(nameValuePairs.get(index).getName(),
                        new FileBody(new File(nameValuePairs.get(index)
                                .getValue())));
        }

        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) 
        {
            page = EntityUtils.toString(resEntity);
            System.out.println("PAGE :" + page);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }