5

我正在尝试从 java spring 控制器调用 web 服务。下面是代码

private void storeImages(MultipartHttpServletRequest multipartRequest) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(
                    "http://localhost:8080/dream/storeimages.htm");
    MultipartFile multipartFile1 = multipartRequest.getFile("file1");
    MultipartEntity multipartEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart("file1",
                    new ByteArrayBody(multipartFile1.getBytes(),
                                    multipartFile1.getContentType(),
                                    multipartFile1.getOriginalFilename()));
    postRequest.setEntity(multipartEntity);
    HttpResponse response = httpClient.execute(postRequest);
    if (response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
    }
}

以上只是部分代码。我正在尝试确定如何在服务器端检索它。在服务器端,我有以下 Spring 控制器代码

@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public ModelAndView postItem(HttpServletRequest request,
                HttpServletResponse response) {
    logger.info("Inside /secure/additem/postitem.htm");
    try {
        // How to get the MultipartEntity object here. More specifically i
        // want to get back the Byte array from it
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new ModelAndView("success");
}

我执行了这段代码,我的控制权转移到了服务器端。但我被困在如何从多方对象中取回字节数组。

编辑要求:这是要求。用户从网站上传图像(已完成并正常工作) 表单提交后控件转到 Spring 控制器(已完成并正常工作) 在 Spring 控制器中,我使用 Multipart 来获取表单的内容。(这已经完成并且正在工作)现在我想调用一个 Web 服务,它将图像字节数组发送到图像服务器。(这需要完成)在图像服务器上,我想接收这个 Web 服务请求从 HTTPServlerRequest 获取所有字段,存储图像并返回(这个需要做)

4

4 回答 4

7

终于解决了。这对我有用。

客户端

private void storeImages(HashMap<String, MultipartFile> imageList) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://localhost:8080/dream/storeimages.htm");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        Set set = imageList.entrySet(); 
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            Map.Entry me = (Map.Entry)i.next(); 
            String fileName = (String)me.getKey();
            MultipartFile multipartFile = (MultipartFile)me.getValue();
            multipartEntity.addPart(fileName, new ByteArrayBody(multipartFile.getBytes(), 
                    multipartFile.getContentType(), multipartFile.getOriginalFilename()));
        } 
        postRequest.setEntity(multipartEntity);
        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        while ((output = br.readLine()) != null) {
            logger.info("Webservices output - " + output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

服务器端

@RequestMapping(value = "/storeimages.htm", method = RequestMethod.POST)
public void storeimages(HttpServletRequest request, HttpServletResponse response)
{
    logger.info("Inside /secure/additem/postitem.htm");
    try
    {
        //List<Part> formData = new ArrayList(request.getParts());
        //Part part = formData.get(0);
        //Part part = request.getPart("file1");
        //String parameterName = part.getName();
        //logger.info("STORC IMAGES - " + parameterName);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Set set = multipartRequest.getFileMap().entrySet(); 
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            Map.Entry me = (Map.Entry)i.next(); 
            String fileName = (String)me.getKey();
            MultipartFile multipartFile = (MultipartFile)me.getValue();
            logger.info("Original fileName - " + multipartFile.getOriginalFilename());
            logger.info("fileName - " + fileName);
            writeToDisk(fileName, multipartFile);
        } 
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

public void writeToDisk(String filename, MultipartFile multipartFile)
{
    try
    {
        String fullFileName = Configuration.getProperty("ImageDirectory") + filename;
        FileOutputStream fos = new FileOutputStream(fullFileName);
        fos.write(multipartFile.getBytes());
        fos.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
于 2012-08-27T21:07:43.807 回答
2

在我的项目中,我们曾经使用com.oreilly.servlets 中的MultipartParser来处理HttpServletRequests对应的multipart请求,如下:

// Should be able to handle multipart requests upto 1GB size.
MultipartParser parser = new MultipartParser(aReq, 1024 * 1024 * 1024);
// If the content type is not multipart/form-data, this will be null.
if (parser != null) {
    Part part;
    while ((part = parser.readNextPart()) != null) {
        if (part instanceof FilePart) {
            // This is an attachment or an uploaded file.
        }
        else if (part instanceof ParamPart) {
            // This is request parameter from the query string
        }
    }
}

希望这可以帮助。

于 2012-08-26T05:01:48.797 回答
2

您可以使用 Springs Mutlipart 支持,而不是手动完成所有这些操作

控制器可以像这样工作(这个例子使用一个命令对象来存储额外的用户输入——(这是一个来自工作项目的例子))。

@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid final DocumentCreateCommand documentCreateCommand,
        final BindingResult bindingResult) throws IOException {
    if (bindingResult.hasErrors()) {
      return new ModelAndView("documents/create", "documentCreateCommand", documentCreateCommand);            
    } else {            
        Document document = this.documentService.storeDocument(
               documentCreateCommand.getContent().getBytes(),
               StringUtils.getFilename(StringUtils.cleanPath(documentCreateCommand.getContent().getOriginalFilename())));
               //org.springframework.util.StringUtils

        return redirectToShow(document);
    }
}


@ScriptAssert(script = "_this.content.size>0", lang = "javascript", message = "{validation.Document.message.notDefined}")
public class DocumentCreateCommand {
    @NotNull private org.springframework.web.multipart.MultipartFile content;       
    Getter/Setter
}

要启用 Spring Multipart 支持,您需要配置一些东西:

web.xml(在 CharacterEncodingFilter 之后和 HttpMethodFilter 之前添加 org.springframework.web.multipart.support.MultipartFilter)

 <filter>
    <filter-name>MultipartFilter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    <!-- uses the bean: filterMultipartResolver -->
</filter>

<filter-mapping>
    <filter-name>MultipartFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

在您的应用程序的 CORE(不是 MVC Servlet)的 Spring 配置中添加这个

<!-- allows for integration of file upload functionality, used by an filter configured in the web.xml -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="filterMultipartResolver" name="filterMultipartResolver">
     <property name="maxUploadSize" value="100000000"/>
</bean>

然后你还需要 commons fileupload 库,因为 Spring MultipartFile 只是某种 Addapter

<dependency>
     <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
</dependency>

有关更多详细信息:@参见Spring 参考,第 15.8 章 Spring 的多部分(文件上传)支持

于 2012-08-26T06:56:26.013 回答
0

处理spring文件到控制器。您需要在您的 app-config.xml 中指明如下:

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

并将代码处理如下

    MultipartEntityBuilder paramsBuilder = MultipartEntityBuilder.create();
    Charset chars = Charset.forName("UTF-8");
    paramsBuilder.setCharset(chars);

    if (null != obj.getFile()){
    FileBody fb = new FileBody(obj.getFile());
    paramsBuilder.addPart("file", fb);
    }

这对于红色多部分

private File getFile(MultipartFile file) {

    try {
        File fichero = new File(file.getOriginalFilename());
        fichero.createNewFile();
        FileOutputStream fos = new FileOutputStream(fichero);
        fos.write(file.getBytes());
        fos.close();
        return fichero;
    } catch (Exception e) {
        return null;
    }

}

我希望这有帮助。

于 2016-07-29T14:21:49.473 回答