必需的MultipartFile参数“文件”不存在-MultipartyEntityBuilder

时间:2019-09-30 06:19:04

标签: java spring http-post httpclient

我正在尝试使用httpclient(Post)将多实体发送到服务器中运行的spring模块。因此它是宁静的Web服务。但是我的代码抛出错误。你能帮我吗?

我已经尝试过了: Spring : File Upload RESTFUL Web Service

HTTPCLIENT FILE:(POST请求)

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控制器:

@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());
}

输出:

Required MultipartFile parameter 'files' is not present

1 个答案:

答案 0 :(得分:0)

我认为ContentType存在问题。

您的控制器找不到名称为“文件”的任何参数

尝试

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);
    }
}

在这里参考more detail