JSP / Servlet无法从textarea获取文本

时间:2015-01-24 19:47:26

标签: java jsp servlets

我试图将带有说明的照片上传到数据库。基本上我已设法上传照片,但说明(评论)始终设为空。

index.jsp包含一个带有文件输入和textarea

的表单
<textarea class="form-control" rows="2" id="comment" name="comment" placeholder="Write something"></textarea>

Servlet代码:

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

    String comment = request.getParameter("comment");

    if(ServletFileUpload.isMultipartContent(request)){
        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));
                    // till now, the photo is being saved in a folder
                    // method addPhoto uploads this photo in database
                    // this method works OK
                    addPhoto((int) request.getSession().getAttribute("id"), UPLOAD_DIRECTORY + File.separator + name , comment);
                }
            }

           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }          
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

如果有人可以帮助我,我如何在数据库中设置照片说明?

1 个答案:

答案 0 :(得分:2)

当请求被编码为&#34; multipart / form-data&#34;时,您必须在解析请求后获取参数。在您的代码中,您可以尝试

for(FileItem item : multiparts){
 if(!item.isFormField()){
   // the logic you already have now
 } else {
   if ("comment".equals(item.getFieldName())) {
        String comment = item.getString();
    // Whatever you have to do with the comment
   }
 }
}