将jsp multipart / form-data形式的输入值发送到servlet

时间:2016-08-30 15:16:39

标签: java forms jsp servlets

我有一个包含表单的JSP

        <form action="upload" method="post" enctype="multipart/form-data">
        <fieldset>
            <input name="nom" class="input-xlarge focused" id="nom" type="text" value=""> 
            <input name="date" class="input-xlarge focused" id="date" type="text" value="">
            <input type="file" name="file" /> 
            <button type="submit" class="btn btn-primary">Envoi</button>
        </fieldset>
    </form>

包含2个字段(nom和date),还要求在服务器上上传文件。

在servlet方面,我有以下内容:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("/")+"imgs/";
    //process only if its multipart content
    if(ServletFileUpload.isMultipartContent(request)){

        String nom = request.getParameter("nom");
        String date = request.getParameter("date");
        log.debug("upload parameters: "+nom+" "+date);


        try {
            List<FileItem> multiparts = new ServletFileUpload(
                                     new DiskFileItemFactory()).parseRequest(request);

            for(FileItem item : multiparts){
                if(!item.isFormField()){
                    String name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }

           //File uploaded successfully
           request.setAttribute("message", "File Uploaded Successfully");
           log.debug("File updated successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
           log.debug("File upload failed: "+ex);
        }          

    }else{
        request.setAttribute("message",
                             "Sorry this Servlet only handles file upload request");
        log.debug("file upload only !");
    }

    //request.getRequestDispatcher("/result.jsp").forward(request, response);

}

文件上传工作正常,但我无法使用request.getParameter检索我的两个参数(nom和date)。

我可以检索multipart / form-data中的参数吗?我怎么能这样做?

1 个答案:

答案 0 :(得分:6)

使用enctype="multipart/form-data"时,您无法使用request.getParameter("nom");直接获取参数。

在这种情况下,表单字段不可用作请求的参数,它们包含在流中,因此您需要从流中获取它们。 一种可能的方法是使用commons-fileupload。以下是官方documentation的示例代码(请参阅“处理上传的项目”部分)

// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = iter.next();

    if (item.isFormField()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}

对于常规表单字段

 // Process a regular form field if (item.isFormField()) {
     String name = item.getFieldName();
     String value = item.getString();
     ... }