输入 TYPE TEXT 来自 JSP 表单的值 (enctype=“multipart/form-data”) 返回 null

2022-09-04 01:25:04

我需要上传图片:

<form method="post" action="hi.iq/register.jsp" enctype="multipart/form-data">
    Name: <input type="text" name="name" value="J.Doe">
    file: <input type="file" name="file-upload">
    <input type="submit">
</form> 

在我的服务中,我给了

response.setContentType("text/html");

PrintWriter out = response.getWriter();    

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

System.out.println("user_id========= "+name);

但 的值返回为 。nameNULL

请帮忙


答案 1

尝试。<input type="text" id="name" name="name" value="J.Doe">

编辑:

使用Apache Commons Fileupload的示例,正如David的答案所建议的那样:

FileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints
// factory.setSizeThreshold(yourMaxMemorySize);
// factory.setRepository(yourTempDirectory);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
// upload.setSizeMax(yourMaxRequestSize);

// Parse the request
List<FileItem> uploadItems = upload.parseRequest( request );

for( FileItem uploadItem : uploadItems )
{
  if( uploadItem.isFormField() )
  {
    String fieldName = uploadItem.getFieldName();
    String value = uploadItem.getString();
  }
}

答案 2

尝试

     FileItemFactory factory = new DiskFileItemFactory();
     ServletFileUpload upload = new ServletFileUpload(factory);
     Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
     File uploadedFile;
     String dirPath="D:\fileuploads";
     while (iterator.hasNext()) {

                    FileItem item = iterator.next();
                    if (!item.isFormField()) {

                        String fileNameWithExt = item.getName();

                        File filePath = new File(dirPath);

                        if (!filePath.exists()) {
                            filePath.mkdirs();
                        }

                        uploadedFile = new File(dirPath + "/" + fileNameWithExt);
                        item.write(uploadedFile);                  
                    }
                    else {
            String otherFieldName = item.getFieldName();
            String otherFieldValue = item.getString()
                    }
               }

它需要Apache和commons-fileupload.jarcommons-io.jar