0

伙计们。在发送带有多部分数据的 POST 请求方面需要帮助。

我有一种在客户端创建请求的方法。这里是:

public void sendMultipart(String cmd , Employee emp) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(baseUrl + cmd);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody f = new FileBody(emp.getPhoto());
    try {
    StringBody s = new StringBody(emp.getLogin());
    builder.addPart("name", s);
    builder.addPart("file", f);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
    }
    uploadFile.setHeader("Accept", "application/json");
        uploadFile.setHeader("Content-type", "application/json");
        uploadFile.setHeader("enctype","multipart/form-data");
        uploadFile.setHeader("accept-charset","UTF-8");
    //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
    //builder.addBinaryBody(emp.getLogin(), emp.getPhoto(), ContentType.MULTIPART_FORM_DATA, "file");
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    try {
        HttpResponse httpResponse =  httpClient.execute(uploadFile);

        int status = httpResponse.getStatusLine().getStatusCode();
        String str = httpResponse.getStatusLine().getReasonPhrase();
    } catch (IOException ex) {
        Logger.getLogger(RestTemplateRequester.class.getName()).log(Level.SEVERE, null, ex);
    }

}

我也有一种方法来处理我的服务器端的请求:

@RequestMapping(value = "photo", consumes = "multipart/form-data")
public @ResponseBody
void uploadFileHandler(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Create the file on server
            File serverFile = new File(name);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
             e.getMessage();
        }
    }
}

在我的上下文中:

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

     <!-- setting maximum upload size -->
    <property name="maxUploadSize" value="100000" />

</bean>

我现在遇到的问题是 408 错误“请求超时”。我的共同目标是 - 将带有文件的 JSON 发送到服务器。我对java中的Web服务非常熟悉,所以我遇到了一些麻烦。拜托,如果有人能给我一点建议,那就太好了。谢谢你。

4

1 回答 1

0

您尝试做的不是上传文件的可接受方式(在 JSON 中嵌入文件)。此外,您的上传文件处理程序不适合处理 JSON,而是只能处理多部分文件和名称作为参数。请查看我之前关于如何使用 Spring MVC Multipart 和 RestTemplate 成功上传文件的 q/a 。

于 2015-03-25T01:20:50.607 回答