如何从httpservletrequest获得多部分实体

时间:2012-08-26 04:07:16

标签: java web-services spring apache tomcat

我正在尝试从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");
}

我执行了这段代码,我的控制权将转到服务器端。但我仍然坚持如何从multipartentity对象返回字节数组。

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

4 个答案:

答案 0 :(得分:5)

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

客户端

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

答案 1 :(得分: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
        }
    }
}

希望这有帮助。

答案 2 :(得分: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 libary,因为Spring MultipartFile只是某种Addapter

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

更多细节: @See Spring Reference, Chapter 15.8 Spring's multipart (fileupload) support

答案 3 :(得分: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;
    }

}

我希望这会有所帮助。