如何从httpservletrequest获得多方性 [英] How to get multipartentity from httpservletrequest

查看:107
本文介绍了如何从httpservletrequest获得多方性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to invoke a webservice from java spring controller. Below is the code

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控制器代码

Above is just partial code. I am trying to determine how to retrieve this on the server side. On the server side i have the following Spring controller code

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

我执行了此代码,并且控制权转到服务器端.但是我一直在坚持如何从多部分对象中获取字节数组.

I executed this code and my control is going to the server side. But i am stuck on how to get back the byte array from the multipartentity object.

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

Edited requirement: Here is the requirement. User uploads the images from website (This is done and working) The control goes to the Spring controller after form submit (This is done and working) In Spring controller I am using Multipart to get the content of the form. (This is done and working) Now i want to call a webservices which will send the image byte array to image server.(This needs to be done) On the image server, i want to receive this webservice request get all the fields from HTTPServlerRequest, store the images and return(This needs to be done)

推荐答案

最终解决了它.这是对我有用的东西.

Finally resolved it. Here is what worked for me.

客户端

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

这篇关于如何从httpservletrequest获得多方性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆