简体   繁体   中英

How to transfer data from JSP to servlet with upload function?

I have a JSP page with an HTML form:

在此处输入图片说明

Here is my code:

<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());
        }

The problem is, I am able to upload the file, but the values which I'm sending are not coming, like fileNames,form_id. I am not getting any values which entered through jsp page as well as hard-coded values.

This snippet if ( !fi.isFormField () ) in your code skips the fields which you are sending and only processes the files that are sent. So to get the fields you need to handle both the cases:

  1. When the field is a form field like radio-button, text, etc.
  2. When the field is a file.

This should give you an idea.

 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM