Summary of this week (file upload, download, mail)

Keywords: Java Session JSP Firefox

File upload

1. Upload Form Restrictions

  • method="post"
  • enctype="multipart/form-data"
  • File form entries need to be added to the form: <input type="file" name="xxx"/>
<h3>${msg }</h3>
 <form action="xxx" method="post" enctype="multipart/form-data">
      //User name; <input type="text" name="username"/><br/>
      //Photo: <input type="file" name="zhaoPian"/><br/>
      <input type="submit" value="upload"/>
    </form>

2. Upload restrictions on Servlet

  • File upload cannot use BaseServlet
  • request.getParametere("xxx"); this method is invalidated when the form enctype="multipart/form-data". It always returns to null.
  • ServletInputStream request.getInputStream(); contains the whole body of the request!

3. Upload three steps

Import jar(commons-fileupload)

  • commons-fileupload.jar
  • commons-io.jar

Related categories:

  • Factory: DiskFile ItemFactory
  • Parser: ServletFileUpload
  • Form entry: FileItem

     1. Create a factory: DiskFileItemFactory = new DiskFileItemFactory ();
     2. Create a parser: ServletFileUpload sfu = new ServletFileUpload(factory);
     3. Use parser to parse request and get FileItem set: List < FileItem > fileItemList = sfu. parseRequest (request);
    

4.FileItem

  1. boolean isFormField(): Is it a regular form item? Return true as a normal form item, if false, as a file form item!
  2. String getFieldName(): Returns the name of the current form item;
  3. String getString(String charset): Returns the value of the form item;
  4. String getName(): Returns the uploaded file name
  5. long getSize(): Number of bytes returned to the uploaded file
  6. InputStream getInputStream(): Returns the input stream corresponding to the uploaded file
  7. void write(File destFile): Save the uploaded file content to the specified file.
  8. String getContentType(); Gets the type of file uploaded

5. Details of upload

  1. Save to WEB-INF! (The goal is not to allow browsers direct access)
  2. Some browsers upload file names that are absolute paths, which need to be cut
  3. Directory scatter

     Hashish Disbandment:  
         Get the int value from the file name, which calls hashCode()
         Its int value is converted to hexadecimal 0-9, A-F
         Get the first two sixteen digits to generate a directory, the directory is two-tier! _________ For example: 1B2C3D4E5F, / 1/B/ save files.
    

6. code

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        /*
         * Upload three steps
         */
        // Factory, set cache, over 20k, save to directory
        DiskFileItemFactory factory = new DiskFileItemFactory(20*1024, new File("F:/f/temp"));
        // Parser
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //sfu.setFileSizeMax(100 * 1024); // Limit the size of a single file to 100K
        //sfu.setSizeMax(1024 * 1024); // Limit the entire form size to 1M
        
        // Parse and get List
        try {
            List<FileItem> list = sfu.parseRequest(request);
            FileItem fi = list.get(1);
            
            /*
             * 1. The path to get the file saved
             */
            String root = this.getServletContext().getRealPath("/WEB-INF/files/");
            /*
             * 2. Generate a two-tier directory
             *   1). Get the file name
             *   2). Get hashCode
             *   3). Forwarding to hexadecimal
             *   4). Get the first two characters to generate the directory
             */
            String filename = fi.getName();//Get the name of the uploaded file
            /*
             * Addressing the Absolute Path Problem of File Names
             */
            int index = filename.lastIndexOf("\\");
            if(index != -1) {
                filename = filename.substring(index+1);
            }
            /*
             * Adding uuid prefix to file name to deal with the problem of file identical name
             */
            String savename = CommonUtils.uuid() + "_" + filename;
            
            /*
             * 1. Get hashCode
             */
            int hCode = filename.hashCode();
            String hex = Integer.toHexString(hCode);
            
            /*
             * 2. Get the first two letters of hex, connect to root, and generate a complete path
             */
            File dirFile = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
            
            /*
             * 3. Create a directory chain
             */
            dirFile.mkdirs();
            
            /*
             * 4. Create directory files
             */
            File destFile = new File(dirFile, savename);
            
            /*
             * 5. Preservation
             */
            fi.write(destFile);
            
            
        } catch (FileUploadException e) {
            if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
                request.setAttribute("msg", "You uploaded more than 100 files KB!");
                request.getRequestDispatcher("/form.jsp").forward(request, response);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

File download

1. Download is to respond to byte data to the client!

 Turn a file into an array of bytes and use response.getOutputStream() to give each to the browser!!!

2. Download Requirements

Two heads and one stream!

  • Content-Type: What MIME type are the files you pass to the client, such as image/pjpeg

     Call the getMimeType() method of ServletContext by the file name, and get the MIME type!
  • Content-Disposition: Its default value is inline, which means open in the browser window! attachment;filename=xxx

    Following filename = is the name of the file displayed in the download box!
  • Stream: File data to download!

    One input stream of your own is OK! ____________
    
    

3. code

@Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /*
         * Two heads and one stream
         * 1. Content-Type
         * 2. Content-Disposition
         * 3. Stream: Data for downloading files
         */
        String filename = "F:/Year of innocence.mp3";
        
        // In order to display Chinese file names in the download box without scrambling!
        String framename = filenameEncoding("Year of innocence.mp3", req);
        
        String contentType = this.getServletContext()
                .getMimeType(filename);//Getting MIME Types by File Name
        String contentDisposition = "attachment;filename=" + framename;
        // One flow
        FileInputStream input = new FileInputStream(filename);
        
        //Set head
        resp.setHeader("Content-Type", contentType);
        resp.setHeader("Content-Disposition", contentDisposition);
        
        // Get the stream bound to the responder
        ServletOutputStream output = resp.getOutputStream();
        
        IOUtils.copy(input, output);//Write the data in the input stream to the output stream.
        
        input.close();
    }
    
    // Used to code the name of the downloaded file! (General Scheme)
    public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
        String agent = request.getHeader("User-Agent"); //Getting Browsers
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?"
                    + base64Encoder.encode(filename.getBytes("utf-8"))
                    + "?=";
        } else if(agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

JavaMail

Note: POP3/SMTP/IMAP is required for general mailboxes. Past mails are likely to be in the trash bin.

1. import jar

mail.jar
activation.jar

2. main categories

javax.mail.Session
javax.mail.internet.MimeMessage
javax.mail.Transport

3. code

  • No accessories
@Test
    public void fun1() throws Exception {
        /*
         * 1. Get session
         */
        Properties props = new Properties();
        props.setProperty("mail.host", "smtp.163.com");
        props.setProperty("mail.smtp.auth", "true");
        
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("itcast_cxf", "itcast");//Account password
            }
        };
        
        Session session = Session.getInstance(props, auth);
        
        /*
         * 2. Create MimeMessage
         */
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//Setting up sender
        msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//Setting up recipients
        //Msg.setRecipients (RecipientType.CC,'itcast_cxf@sohu.com'); //Set Cc
        //Msg.setRecipients (RecipientType.BCC,'itcast_cxf@sina.com'); //Set secret delivery
        
        msg.setSubject("This is from ITCAST Test mail");
        msg.setContent("This is a spam!", "text/html;charset=utf-8");
        
        /*
         * 3. hair
         */
        Transport.send(msg);
    }
  • There are accessories.
@Test
    public void fun2() throws Exception {
        /*
         * 1. Get session
         */
        Properties props = new Properties();
        props.setProperty("mail.host", "smtp.163.com");
        props.setProperty("mail.smtp.auth", "true");
        
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("itcast_cxf", "itcast");
            }
        };
        
        Session session = Session.getInstance(props, auth);
        
        /*
         * 2. Create MimeMessage
         */
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//Setting up sender
        msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//Setting up recipients
        
        msg.setSubject("This is from ITCAST Test mail with attachments");
        
        /*
         * When sending mail containing attachments, the body of the mail is in the form of multiple components!
         * 1. Create a multi-component component content! Mime Multipart
         *   MimeMultipart It's a collection that loads multiple main components!
         * 2. We need to create two body parts, one for text content and the other for attachments.
         *   The main part is called MimeBodyPart.
         * 3. Set MimeMultipart to the content of MimeMessage!
         */
        MimeMultipart list = new MimeMultipart();//Create multipart content
        
        // Create MimeBodyPart
        MimeBodyPart part1 = new MimeBodyPart();
        // Setting the content of the main component
        part1.setContent("This is a spam with attachments.", "text/html;charset=utf-8");
        // Adding body parts to collections
        list.addBodyPart(part1);
        
        
        // Create MimeBodyPart
        MimeBodyPart part2 = new MimeBodyPart();
        part2.attachFile(new File("F:/f/Bai Bing.jpg"));//Setting the contents of attachments
        part2.setFileName(MimeUtility.encodeText("Beauty.jpg"));//Set the name of the file to display, where encodeText is used to deal with Chinese scrambling problem
        list.addBodyPart(part2);
        
        msg.setContent(list);//Set it to mail as the content of the mail.
        
        /*
         * 3. hair
         */
        Transport.send(msg);        
    }

Posted by ironman on Wed, 15 May 2019 14:38:58 -0700