我正在尝试使用httpclient(Post)将多实体发送到在服务器中运行的spring模块。因此它是宁静的Web服务。但是我的代码抛出错误。你能帮我吗?
我已经尝试过了:
Spring : File Upload RESTFUL Web Service
HTTP客户端文件:(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);
}
}
弹簧控制器:
@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
最佳答案
我认为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
关于java - 必需的MultipartFile参数"file"不存在-MultipartyEntityBuilder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58162393/