Java file upload and download

1, File upload  

File upload refers to saving the file data on the browser side directly to the disk on the server side to reduce the pressure on the database. It only needs to record the file identification information in the database to make the data operation more flexible and diverse.

Principle: obtain the input stream through the request object, read the data on the browser side and save it to the server side.

Conditions:

1. The request method must be post, the inpu t component with type="file" is required, and the name needs to be defined;

2. The form must be set with enctype = "multipart / form data";

3.ajax asynchronous file upload: if you want to upload files using Ajax, you need to use the FormData object as data instead of the serialize method of form (because the data obtained by the serialize method is a string, which does not support binary data transmission, so you can't upload files)

	var formdata = new FormData();//Create a new FormData object
	//The data attribute in Ajax is formdata
	formdata.append('name','value'); //Use the append method to assign values to the formdata object
	$.ajax({
	type:'post',
	url:'url',
	contentType:false, //By default, the value of processData is true, which means that the data uploaded as an object will be converted into a string for upload. When uploading a file, it does not need to be converted to a string, so it should be changed to false
	processData:false, //A similar attribute to contentType is dataType, which represents the format of the data expected to be received from the back end, generally json, text... Etc., while contentType corresponds to dataType, which represents the format of the data sent by the front end
	data:formdata,
	success:function(){
		
}
})

  Precautions for uploading:

1. In order to ensure the security of the server, the uploaded files 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, the following methods are used to generate a unique file name for the uploaded file: (uuid is used in this section)

(1)-uuid     (2) - timestamp     (3)   - md5   (4) Bit operation algorithm     (5) txt

3. Limit the maximum value of uploaded files;

4. The type of uploaded file can be limited. When the uploaded file name is received, judge whether the suffix is legal.

Implementation of back-end code for uploading files: the code is in servlet.java file

Implementation process:

1. Get form data with file type

2. Open the file save directory

3. Use Apache file upload component to handle file upload (Trilogy)

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out  =  response.getWriter();
        //Judge whether the uploaded form is an ordinary form or a form with files. If it is a form with files, return true; otherwise, return false;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            throw new RuntimeException("Form must be multiparty/form-data");
        }
        //Create a storage directory for uploaded files. For security, it is recommended to use the WEB-INF directory, which users cannot access
        String uploadPath = this.getServletContext().getRealPath("WEB-INF/upload");
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            //If the directory does not exist, create such a directory
            dir.mkdir();
        }
        //File upload temporary directory
        String tmpPath = this.getServletContext().getRealPath("WEB-INF/tmp");
        File tmpFile = new File(tmpPath);
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        try {
            //Using Apache file upload component to process file upload steps:
            //1. Create a DiskFileItemFactory factory
            DiskFileItemFactory factory = DiskFileItemFactoryUtils.getDiskFileItemFactory(tmpFile);
            //2. Create a file upload parser
            ServletFileUpload sfu = getServletFileUpload(factory);
            //3. Analyze the form and upload the contents of file items
            String msg = uploadParseRequest(sfu,request,uploadPath);
            out.write("<script language='javascript'>window.alert('File uploaded successfully');</script>");
            request.getRequestDispatcher("upload.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

  @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

Method class:  

public class DiskFileItemFactoryUtils {
    private static DiskFileItemFactory factory;
    static{
        factory = new DiskFileItemFactory();
        //Set a buffer through the factory. When the uploaded file is larger than the buffer, put it into the temporary file
        factory.setSizeThreshold(1024 * 1024*5);//The cache size is 1M
    }
    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        factory.setRepository(file);//A File is required to save the temporary directory
        return factory;
        }
}

 public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");   //Dealing with garbled code
        //Monitor file upload progress
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead: the size of the file that has been read
            //pContentLength: file size
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("Total size:" + pContentLength + "Uploaded:" + pBytesRead);
            }
        });
        //If the following is not set, it is the default value
        upload.setFileSizeMax(1024 * 1024 * 5);    //Sets the maximum value for a single file
        upload.setSizeMax(1024 * 1024 * 5);    //Set the total size of files that can be uploaded
        return upload;
    }
 public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws Exception {
        String msg = "";
        int isLoad=1;
        //Monitor file upload progress
        //4. The servlet fileUpload parser is used to parse the uploaded data. The parsing result returns a list < FileItem > collection, and each FileItem corresponds to an input item of the Form
        List<FileItem> fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
             //Judge whether it is file type data. If yes, false is returned; getFieldName is the name of the input button at the front end of the processing, and. trim() removes the space before and after it
            if (fileItem.isFormField()) {
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");//Deal with garbled code
                isLoad = Integer.parseInt(value);             //Obtain file downloadable permission
                System.out.println(name + ":" +" "+isLoad);
            } else {
                //The file names submitted by different browsers are different. Some browsers submit file names with paths
                String uploadFileName = fileItem.getName().trim();
                System.out.println("Uploaded file name:" + uploadFileName);
                if (uploadFileName.equals("") || uploadFileName == null) {
                    continue;//The file name does not exist and cannot be saved, (unknown file)
                }
             
                //Get the uploaded file name / images/girl/paojie.jpg
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                //Gets the suffix of the file
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                System.out.println("file information[File name:" + fileName + "----file type" + fileExtName+"]");

                //UUID.randomUUID(), randomly generate a unique universal identification code; UUID (universal code that can be uniquely identified) can be used to ensure that the file name is unique;
                String uuidPath = UUID.randomUUID().toString();
                String realFile = uuidPath+"_"+fileName;
                //Where? uploadPath  
                fileItem.write(new File(uploadPath,realFile));
               
                msg="File uploaded successfully!";
                fileItem.delete();//Upload succeeded. Clear the temporary file

            }
        }
        return msg;
    }

Upload file front-end code implementation

If you want to download multiple files, you can use multiple to represent multiple files in the file component, or you can directly add several more file components.

<form name="form02" enctype="multipart/form-data" action="upload" method="post" >
            <input type="radio" name="authority" value="0">Download only by yourself<br/>
            <input type="radio" name="authority" value="1">Everyone can download<br/>
            <input type="file" name="photo" multiple/><br/>
            <input type="submit" value="upload" /><br/>
    </form>

2, File download

File download means that the file resources on the server side are written back to the browser side through I/O stream, and the customer uses hyperlink to download.

Backend code implementation:

            String fileName = request.getParameter("fileName");
            System.out.println(fileName);
            String dir = this.getServletContext().getRealPath("WEB-INF/upload");
            System.out.println(dir);
            File file = new File(dir,fileName);
            System.out.println(file);
            if(!file.exists()){
                System.out.println("file"+fileName+"non-existent");  //File.separator?
                return;
            }
            //Solve the problem of Chinese garbled code
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //Important parameters: set the response header and control the browser to download the file
            response.setHeader("content-disposition","attachment;filename="+fileName);
            FileInputStream fis = new FileInputStream(file);
            ServletOutputStream os =  response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer))>0){
                os.write(buffer,0,len);
            }
            fis.close();
            os.close();
            PrintWriter out = response.getWriter();
            out.print("successful");
            request.getRequestDispatcher("downLoad.jsp").forward(request,response);

Front end code implementation:

1. This code uses JSTL and needs to import jar package;

2. Different users have different download permissions;

3. When uploading a file, you need to write the file attributes into the storage before you can quickly read out the file. In combination with mybatis file upload and download, the specific implementation is in mybatis - file upload and download

<div id="downLoad" style="position:relative;background-color:lightskyblue;width:750px;height:850px;margin:auto;padding:20px;">

    <c:forEach items="${DL}" var="dl">
        <c:url value="download" var="downUrl">
            <c:param name="fileName" value="${dl.uuid}"></c:param>
        </c:url>
        <p>${dl.fileName}<a href="${downUrl}&flag=load">download</a>&nbsp;&nbsp;&nbsp;
            <c:if test="${dl.uploaderId eq user.id}">
            <a href="${downUrl}&flag=delete&userId=${user.id}">delete</a>
            </c:if>
        </p>

    </c:forEach>

</div>

Keywords: Java intellij-idea

Added by Infinitus 8 on Sun, 05 Dec 2021 13:25:42 +0200