servlet request message body, file upload

Request message body

The message body of the request can be text or binary

Plain text message body

    String value = req.getParameter ("parameter name" );
     // The parameter name contains:
         // What does the hyperlink correspond to? The parameter name after the number is good
         // For the form, the parameter is the value of the name in the form control
     // getParameter ("parameter name"); the function can handle hyperlinks, form input boxes, radio boxes, radio drop-down menus, text Field 

    String [] values = req.getParameterValues ​​("name value" );
     // getParameterValues ​​("name value"); The function handles the check boxes and multi-select drop-down menus in the form

Binary message body

    // Get the part object part of the file object 
        = request.getPart ("photo" );
     // Get the file name of the file object 
        String fileName = part.getSubmittedFileName (); 

    // getParameter This method cannot be used when transferring data in binary mode Get the value in the input box.
    // After adding @MultipartConfig annotation, using getParameter method, there is no difference between text and binary

upload files

File operations-client settings

  1. Submitted as post

  2. enctype = "multipart / form-date" (enctype specifies how form data should be encoded before being sent to the server)

The first step of file upload

  1. Set the form submission method to post encoding method to enctype = "multipart / form-data"

  2. Write a servlet that handles file uploads. Tell the web container that the servlet can process files.

  3. Get the value of each form element separately (part)

// Get the file object's part 
    Part part = request.getPart ("photo" ); 

// Get the file name of the file object 
    String fileName = part.getSubmittedFileName (); 

// Get the file's suffix name 
    String ext = fileName.substring (fileName.lastIndexOf ("." )); 

// Get uuid 
    String uuid = UUID.randomUUID (). toString (); 

// Get new file name 
    String newFileName = uuid + ext; 

// Get the address where the file is stored 
    String path = this .getServletContext (). getRealPath ("Folder for uploading files" ); 

// Create a file object 
    File file = new File (path); 

// If there is no such imgs folder
    if (! file.exists ()) { 
        file.mkdir (); 
    } 

// Get the path to save the file 
    String save_path = path + File.separator + newFileName;
     // File.separator-> System-generated file separator 

// upload File 
    part.write (save_path);

other

  1. Everything that comes from the client is a string

Guess you like

Origin www.cnblogs.com/-Archenemy-/p/12709969.html