0

如何使用多部分表单数据(@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.
4

1 回答 1

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();
    }
于 2014-04-14T12:21:55.777 回答