如何使用Apache httpclient 3.x将multipart文件和文件名传递给post方法?

时间:2016-09-15 09:39:10

标签: java spring shiro apache-commons-httpclient

服务代码:

    @RequestMapping(value="/uploadFile", method=RequestMethod.POST, consumes = "multipart/form-data")
public String uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("filePath") String filePath){
//logic here
}

部分客户端代码:

public static synchronized String responseOfPost(String restUrl, FileSystemResource file,String filePath) {
    PostMethod post = new PostMethod(restUrl);
    HttpClient client = new HttpClient();
    post.setParameter("filePath", filePath);
    try {
        Part[] parts = {new FilePart("file",file.getFile())};
        post.addRequestHeader("Content-Type", "multipart/form-data; boundary=Endedlogging");
        if (file != null) {
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        }
        client.executeMethod(post);
        String response = post.getResponseBodyAsString();
    } catch (final IOException e) {
        e.printStackTrace();
    } 
    return null;
}

这是我得到的错误:

org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:251)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:96)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)

如何在客户端代码中将多部分文件(“file”)和filePath(“filePath”)传递给POST方法? NOT FROM UI

1 个答案:

答案 0 :(得分:1)

I'm also getting the exception like FileNotFoundException with nearly same code as your's.So can you try with this change,it maybe helpful.

Part[] parts = {new FilePart(file.getName(),file)};