SpringMVC-FileUpload - The request sent by the cli

2019-03-02 20:08发布

I've seen couple of qts on the same topic. But I didn't find any clue of this error.

I am working on a POC and following the link below. http://spring.io/guides/gs/uploading-files/

As mentioned in the above tutorial, in standalone mode[spring embeded Tomcat] it is working absolutely fine. But I want to deploy it as webapplication. So, I have created a separate SpringMVC project and added the following controller.

Controller file

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name, 
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = 
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

}

I've written the following client ( As I don't want to use RestTemplate here).

Service Client

private static final String URL_GET = "http://localhost:8080/SpringMVC/upload";
static String URL = "http://localhost:8080/SpringMVC/upload";

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("C:/DevEnvProject/eclipse/workspace_exp/OCR/log4j.properties");
    testGet();
    testPOST();
}

private static void testGet() throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(URL_GET);
    HttpResponse response = httpClient.execute(httpGet, localContext);

    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String sResponse = reader.readLine();

} 

static void testPOST() {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(URL);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("name", new StringBody("testIcon.png"));
        entity.addPart("file", new FileBody(new File("C:/testIcon.png")));
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost, localContext);


        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse = reader.readLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I couldn't make a successful call to the POST endpoint. Everytime, I'm getting the following exception.

400 Bad Request - The request sent by the client was syntactically incorrect

'GET' call is working fine. I compared the the log of the 'POST' request with the same 'POST' request which I got while testing with standalone approach as mentioned in the spring tutorial. Didn't find any diff in the request part.

I know that I'm quite verbose in this post. I wanted to give as much context info as possible. Please help.

Thanks

1条回答
啃猪蹄的小仙女
2楼-- · 2019-03-02 20:49

There are 2 things you need to do:

First, add the Apache Commons FileUpload library to your class path. If you use maven, you can get the dependency here. If you don't, you can still download the jar and add it manually.

Second, you have to declare a MultipartResolver bean in your context with name multipartResolver. With Apache Commonds FileUpload, you can use CommonsMultipartResolver. For example, with Java config, that would be

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(); 
    // set any fields
    return commonsMultipartResolver; 
}

With XML config,

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- set any properties -->
</bean>

This is further documented in the Spring official documentation.

查看更多
登录 后发表回答