Java web learning summary -- file upload and download

Posted by bskauge on Mon, 09 Dec 2019 14:02:57 +0100

Catalog

@
Hey, Xiong dei, you have to know that in Web development, file upload and download are very common functions. As for file upload, browser upload [file transfer in the form of stream] - server side - > servlet get the input stream of uploaded file - > parse the request parameters. In this series of processes, page's brain shell hurts, so I recommend opening apache The source tool common fileUpload is a file upload component. The jar package of the common fileUpload upload component can be downloaded from the apache official website or found under the lib folder of struts (don't ask me why, because even if you ask me, I won't tell you that the struts upload function is based on this implementation. Of course, you don't have to use struts Less), and you won't go to the lib directory to find it. Secondly, common file upload depends on the common IO package, so you need to download and use it together!

1. Establishment of file upload environment

You can directly search the Apache official website to download the jar package, but now it's more popular to manage the jar package by mawen (don't understand mawen? Come on, there are still many things to learn. mawen must be learned and it's easy to learn. You can't stop using mawen. It's so convenient. If you learn mawen, you will understand why mom doesn't have to worry about Xiaoming taking the U disk to copy Xiaohong's jar Wrapped)



At this time, the common IO package that common file upload depends on is downloaded in the same way, and then the project is created and jar package is introduced

2. File upload code implementation

2.1JSP code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>                                          
        <form action="UploadServet" method="post"  enctype="multipart/form-data">
            Student ID:<input name="sno" /><br/>
            Full name:<input name="sname" /><br/>
            Upload photos: <input type="file"  name="spicture"/>
            <br/>
            <input type="submit" value="register"/>
        </form>
        <a href="DownloadServlet?filename=MIME.png">MIME</a>
        
</body>
</html>

2.2 servlet code

package org.student.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServet
 */
public class UploadServet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadServet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        // upload
        // request.getParameter("sname")
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {// Determine whether the form in the foreground has mutipart attribute
//              FileItemFactory factory = new DiskFileItemFactory();
                DiskFileItemFactory factory = new DiskFileItemFactory();
                
                ServletFileUpload upload = new ServletFileUpload(factory);
                
                //Set the size of temporary files used for uploading DiskFileItemFactory
                factory.setSizeThreshold(10240);//Set the temporary buffer file size to 10
                factory.setRepository(new File("D:\\study\\uploadtemp"));//Set directory for temporary files
                //Control the size of the uploaded single file 20KB ServletFileUpload
                upload.setSizeMax(20480);//Byte B
                Thread.sleep(3000);
                
                // Parse all request fields in the form through parseRequest and save them to the items collection (sno sname passed in the foreground
                // Structure is saved in items.)
                List<FileItem> items = upload.parseRequest(request);
                // Traverse data in items (item = SnO sname texture)
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    String itemName = item.getFieldName();
                    int sno = -1;
                    String sname = null;
                    // Determine whether the foreground field is a normal form field (sno sname) or a file field

                    // request.getParameter() -- iter.getString()
                    if (item.isFormField()) {
                        if (itemName.equals("sno")) {// Judge whether the item is sno sname or texture according to the name attribute?
                            sno = Integer.parseInt(item.getString("UTF-8"));
                        } else if (itemName.equals("sname")) {
                            sname = item.getString("UTF-8");
                        } else {
                            System.out.println("Other fields xxx.....");
                        }
                    } else {// spicture 123
                            // File upload
                            // The file Name getFieldName is the Name value of the common form field
                            // getName() is the get filename
                        String fileName = item.getName();//a.txt   a.docx   a.png
                        String ext = fileName.substring(  fileName.indexOf(".")+1 ) ;
                        if(!(ext.equals("png") || ext.equals("gif") ||ext.equals("jpg"))) {
                            System.out.println("Wrong picture type! Format can only be png gif  jpg");
                            return ;//termination
                        }
                        // Get file content and upload
                        // Define file path: specify the upload location (server path)
                        // Get server path D:\study\apache-tomcat-8.5.30\wtpwebapps\UpAndDown\upload
                        // String path =request.getSession().getServletContext().getRealPath("upload") ;
                        String path = "D:\\study\\upload";

                        File file = new File(path, fileName);
                        
                    

                        item.write(file);// upload
                        System.out.println(fileName + "Upload succeeded!");
                        return;
                    }
                }

            }

        }
        catch (FileUploadBase.SizeLimitExceededException e) {//SizeLimitExceededException is a subclass of FileUploadException
            System.out.println("Upload file size exceeds the limit! Max 20 KB");
        }
        catch (FileUploadException e) 
        {
            e.printStackTrace();
            
        }
        
        // Parsing request
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

####2.3 precautions for file upload:
1. To ensure the security of the server, the uploaded file should be placed in a directory that cannot be directly accessed by the outside world, such as the WEB-INF directory.

2. To prevent file overwriting, a unique file name should be generated for the uploaded file.
  
3. If the uploaded directory is named upload under wtpwebapps in Tomcat directory, it is as follows:


Note:
3.1. If the code is modified, it will be deleted when tomcat is restarted
Reason: when the code is modified, tomcat will recompile a new class and redeploy (recreate various directories)

3.2. If the code is not modified, it will not be deleted
Reason: no code modification, class is still the previous class

Therefore, in order to prevent the upload directory from losing: a. virtual path

b. directly change the upload directory to a non tomcat directory

4. Limit upload: limit type and size. Note that the file restrictions are written before parseRequest

3. About downloading

Download: no need to rely on any jar
A. request (address a form), request Servlet
B. the Servlet converts the file into an input stream through the address of the file and reads it into the Servlet
c. output the file that has just been converted to input stream to the user through output stream
Note: two response headers are required to download the file:

response.addHeader("content-Type","application/octet-stream" );//MIME type: binary (any file)
response.addHeader("content-Disposition","attachement;filename="+fileName );//fileName contains the file suffix: abc.txt

File download code:

package org.student.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //Get the file name to download
        String fileName = request.getParameter("filename") ;//form  ,a  href, ...Server?a=b
        
        
        //Download File: message header needs to be set
        response.addHeader("content-Type","application/octet-stream" );//MIME type: binary (any file)
        response.addHeader("content-Disposition","attachement;filename="+fileName );//fileName contains the file suffix: abc.txt
        
        //The Servlet converts the file into an input stream through the address of the file and reads it into the Servlet
        InputStream in = getServletContext().getResourceAsStream("/res/MIME.png") ;
        
        //Output the file that has just been converted to input stream to the user through output stream
        ServletOutputStream out = response.getOutputStream() ;
        byte[] bs = new byte[10];
        int len=-1 ;
        while(  (len=in.read(bs)) != -1) {
            out.write(bs,0,len);
        }
        out.close();
        in.close();
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Here, to the happiest moment!!! The source code and notes for file upload and download have been packed with QnQ:
Link: https://pan.baidu.com/s/1oyyekctcvy3avtsjnkiuq extraction code: 30e7

Topics: Java Apache Tomcat Struts