Abhinav
Abhinav

Reputation: 1027

Http Client POST upload file - MultipartException: Curren t request is not a multipart request

I need to test file upload using httpclient 4.5

Below method is being used to upload a file:

public Response postwithFile(String url, File file) {
        HttpPost postMethod = new HttpPost(PropertyUtil.loadEnvironment().getBaseUrl() + url);
        postMethod.setHeader("Content-Type","multipart/form-data");
        FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
        //_addAuthHeader(postMethod);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // fileParamName should be replaced with parameter name your REST API expect.
        builder.addPart("upfile", fileBody);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity) ;
        return execute(postMethod);
    }

The file do not have any extension but the content of the file is JSON.

On calling above method I receive 500 error with below exception in server logs:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Curren
t request is not a multipart request                                                                                                                            
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)  

Can anyone please help where I am doing wrong?

Upvotes: 0

Views: 449

Answers (1)

vinay chhabra
vinay chhabra

Reputation: 587

Use following

 builder.addBinaryBody(
        "upfile",
        new FileInputStream(file),
        ContentType.APPLICATION_OCTET_STREAM,
        file.getName()
    );

instead of

 builder.addPart("upfile", fileBody);

Also following is no longer required as it is also deprecated:-

FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);

Upvotes: 1

Related Questions