0

I'm trying to send the multipartentity using httpclient(Post) to spring module which is running in server. So it is restful web service. But my code is throwing error. Can you please help me out?

I already tried this: Spring : File Upload RESTFUL Web Service

HTTPCLIENT FILE:(POST REQUEST)

public class MultiFile {
public static void main(String args[]) throws ClientProtocolException, IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8080/RESTapi/student/addimage");
File file = new File("/Users/prabhu-pt3030/Desktop/eclipse-workspace-new/testing/target/classes/tes/javaFile123.txt");
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
FileBody filebody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
entitybuilder.addPart("files", filebody);
HttpEntity mutiPartHttpEntity = entitybuilder.build();  
httppost.setEntity(mutiPartHttpEntity); 
HttpResponse httpresponse = httpclient.execute(httppost);
}
}

Spring controller:

@RequestMapping(value="/student/addimage",method=RequestMethod.POST,headers = "content-type=multipart/form-data")
public  void Addingimage(@RequestParam(value="files") MultipartFile files)
{
 //System.out.println(files.isEmpty());
}

Output:

Required MultipartFile parameter 'files' is not present

1 Answers1

0

I think there is issue with ContentType.

Your Controller is not able to find any param with name "files"

Try this

public class MultiFile {
    public static void main(String args[]) throws ClientProtocolException, IOException
    {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://localhost:8080/RESTapi/student/addimage");
        File file = new File("/Users/prabhu-pt3030/Desktop/eclipse-workspace-new/testing/target/classes/tes/javaFile123.txt");
        MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
        FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
        entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entitybuilder.addPart("files", filebody);
        HttpEntity mutiPartHttpEntity = entitybuilder.build();  
        httppost.setEntity(mutiPartHttpEntity); 
        HttpResponse httpresponse = httpclient.execute(httppost);
    }
}

Refer here for more detail

MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
  • No! I'm getting the same error. I changed the contentype to default_binary and even with deafult_text. But still getting the same error – Prabhu Sarathy Sep 30 '19 at 07:29