如何使用上传功能将数据从JSP传输到servlet?

时间:2018-08-01 12:25:05

标签: java jsp servlets file-upload

我有一个带有HTML表单的JSP页面:

enter image description here

这是我的代码:

<form method="post" action="UploadServlet" name="upload" enctype="multipart/form-data" >

            Select file to upload: <input type="file" name="uploadFile" >
            <input type="text" name="fileNames" > 
        <input type="hidden" name="form_id" value="652973" > 
            <br/><br/> 
            <input type="submit" value="Upload" />

        </form>

web.xml

<display-name>UploadServletApp</display-name>
  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>net.code.upload.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

UploadServlet.java

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

        PrintWriter writer = response.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    String paths="C:\\Uploaded_FIle\\";
    factory.setRepository(new File(paths));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    //String uploadPath = getServletContext().getRealPath("")+ File.separator + UPLOAD_DIRECTORY;
    String uploadPath =paths+File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }
try {

            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while ( iter.hasNext () ) 
             {
                FileItem fi = (FileItem)iter.next();
                if ( !fi.isFormField () )  {
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    File file = new File( uploadDir + "yourFileName") ;
                    fi.write( file ) ;
                     }
             }

            request.setAttribute("message", "Upload has been done successfully!\n"  + uploadDir  + "<br>");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }

问题是,我能够上传文件,但是我要发送的值没有出现,例如fileNames,form_id。我没有从jsp页面输入的任何值以及硬编码的值。

1 个答案:

答案 0 :(得分:0)

您的代码中的这段代码if ( !fi.isFormField () )跳过了您要发送的字段,只处理已发送的文件。因此,要获取字段,您需要处理两种情况:

  1. 该字段是单选按钮,文本等表单字段时。
  2. 该字段是文件时。

这应该给你一个主意。

 try {
    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();
            // ... (do your job here)
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            InputStream fileContent = item.getInputStream();
            // ... (do your job here)
        }
    }
} catch (FileUploadException e) {
    throw new ServletException("Cannot parse multipart request.", e);
}