使用REST上传多个文件

kavita:

我的html中有一个input type = file标记,它允许用户选择多个文件。表单的操作是REST Web服务:

@POST
@Path("savefile")
@Produces ({MediaType.TEXT_PLAIN})
public String createObjects(
        @FormDataParam("datafile") FormDataMultiPart file,
        @FormParam("username") String unm
        //@Context HttpServletRequest request
        ){....}

最初,我使用请求对象检索请求中的所有FileItem,然后将其保存到服务器。没问题。现在,我想与文件一起发送字符串数据。为此,我读到参数必须为FormDataParam类型。因此,我添加了该参数。这是我的客户代码:

<form id="form1" action="http://comp1:8080/RestWSGS/jersey/UploadFiles/savefile"
        enctype="multipart/form-data" method="post">
        <input name="username" type="text" style="display:none" value="abc"/>
  <input id="loadId" multiple="multiple" 
        type="file" name="datafile" required="required" autofocus="autofocus"
        onchange="selectFiles(this)"/>
  <div>
    <input style="display: none;" type="submit" value="Send">
  </div>
 </form>  

我不确定文件参数的类型必须是什么才能允许多个文件????是file参数给了我多个文件,还是必须恢复为@Context注入?如果是这样,我将如何检索字符串参数?

欢迎任何帮助!

编辑:我已将我的REST ws修改为以下内容:

@POST
@Path("savefile")
//@Consumes (MediaType.MULTIPART_FORM_DATA)
public void createObjects(
        //@FormDataParam("datafile") FormDataMultiPart file,
        //@FormParam("username") String unm
        @Context HttpServletRequest request
        )
{
    try
    {
        FileHandler f;
        f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\")  + "/mylog.log");
        logger.addHandler(f);

    }
    catch (SecurityException e1)
    {
        logger.info(e1.getMessage());

    }
    catch (IOException e1)
    {
        logger.info(e1.getMessage());
        //e1.printStackTrace();
    }


    ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ;
    ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring
    (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2);
    String user = request.getParameter("username");
    logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH);


    try
    {
        for (Part part : request.getParts())
        {
                try
                {
                    logger.info("part = " + part.getName());
                    if (!part.getName().equalsIgnoreCase("username"))
                    {
                        String fileName = processFileName(part.getName());
                        part.write(new File(ApplicationConstants.ROOTPATH + user + "\\" + fileName).getPath());
                    }

                    else
                    {
                         user = request.getParameter("username");
                         logger.info("user = " + user);
                    }
                }
                catch (IOException e)
                {
                    logger.info(e.getMessage());

                }
        }
    }
    catch (IOException e)
    {

    }
    catch (ServletException e)
    {

    }
}

但是我总是从request.getParameter(“ username”)中获取空值。我不知道怎么了!以multipart / form-data形式发送其他数据是否非法?我在这里需要一些指示。请提出对此代码的任何改进。

kavita:

以下是适用于我的解决方案。使用多部分/表单数据请求时,可以使用部分中的输入流来访问请求部分。我想将一个字符串和一些文件发送到我的REST Web服务。我在几个网站上找到了一个ServletFileUpload / FIleItem示例,但我无法检索该字符串(如果所有数据都不属于文件,我会认为这是一个异常类型)。因此,我将Web服务修改为以下内容,而不是可以处理字符串和某些文件:

    private static  Logger   logger = Logger.getLogger("UploadFiles");
@POST
@Path("savefile")
public void createObjects(@Context HttpServletRequest request)
{
    try
    {
        FileHandler f;
        f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\")  + "/mylog.log");
        logger.addHandler(f);

    }
    catch (SecurityException e1)
    {
        logger.info(e1.getMessage());

    }
    catch (IOException e1)
    {
        logger.info(e1.getMessage());
    }
    ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ;
    ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring
    (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2);
    String user = request.getParameter("username");
    logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH);
    logger.info("username" + user);
    try
                {
        for (Part part : request.getParts())
        {

                    logger.info("part = " + part.getName());
                    if (!part.getName().equalsIgnoreCase("username"))
                    {
                        try {
                        BufferedInputStream in = new BufferedInputStream(part.getInputStream());
                        String filename = getFilename(part);
                        boolean success = (new File(ApplicationConstants.ROOTPATH + user + "\\")).mkdir();
                        if (success) {
                        System.out.println("Directory: " + ApplicationConstants.ROOTPATH + user .trim()+ "\\" + " created");
                        }  
                        else
                        {
                            System.out.println("not created");
                        }
                        FileOutputStream out = new FileOutputStream(ApplicationConstants.ROOTPATH + user  + "\\" + filename);

                        byte[] data = new byte[1000];
                        int bytesRead = 0;
                        int offset = 0;
                        while (offset < part.getSize())
                        {
                          bytesRead = in.read(data);
                          if (bytesRead == -1)
                          {
                              break;
                          }
                          offset += bytesRead;
                           out.write(data);
                        }

                        in.close();

                        if (offset != part.getSize())
                        {
                          throw new IOException("Only read " + offset + " bytes; Expected " + part.getSize() + " bytes");
                        }
                        out.flush();
                        out.close();
                        }
                        catch (Exception e) 
                        {
                            logger.info(e.getMessage());
                        }
                    }
                    else
                    {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
                        StringBuilder value = new StringBuilder();
                        char[] buffer = new char[1024];
                        reader.read(buffer);
                        value.append(buffer);
                         user = value.toString().trim();
                         logger.info("user = " + value);
                    }

}
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (ServletException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

希望这对某人有帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章