SpringMVC-FileUpload - 客户端发送的请求在语法上是不正确的

时间:2013-11-24 18:22:24

标签: java spring rest spring-mvc

我在同一主题上看过几个qts。但我没有找到任何关于这个错误的线索。

我正在开发POC并按照以下链接进行操作。 http://spring.io/guides/gs/uploading-files/

正如上面的教程所提到的,在独立模式[spring embeded Tomcat]中,它工作得非常好。 但我想将其部署为webapplication。所以,我创建了一个单独的SpringMVC项目并添加了以下控制器。

控制器文件

@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.";
        }
    }

}

我编写了以下客户端(因为我不想在这里使用RestTemplate)。

服务客户端

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

我无法成功调用POST端点。每次,我都会遇到以下异常。

400错误请求 - 客户端发送的请求在语法上不正确

'GET'电话工作正常。我将'POST'请求的日志与我在使用Spring教程中提到的独立方法测试时获得的相同'POST'请求进行了比较。在请求部分没有找到任何差异。

我知道我在这篇文章中很啰嗦。我想尽可能多地提供上下文信息。请帮忙。

由于

1 个答案:

答案 0 :(得分:6)

您需要做两件事:

首先,将Apache Commons FileUpload库添加到类路径中。如果您使用maven,则可以获得依赖关系here。如果不这样做,您仍然可以下载jar并手动添加它。

其次,您必须在名称为MultipartResolver的上下文中声明multipartResolver bean。使用Apache Commonds FileUpload,您可以使用CommonsMultipartResolver。例如,使用Java配置,那将是

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

使用XML配置

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

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

Spring official documentation进一步记录了这一点。