Upload key ideas:

1. To ensure server security, upload files to a directory that cannot be accessed directly, for example, the WEB-INF directory.

2. To prevent file overwriting, create a unique file name for the uploaded file.

3. To prevent too many files in a directory, use the hash algorithm to split the storage.

4. Limit the maximum number of uploaded files.

5, to limit the type of the uploaded file, when receiving the uploaded file name, determine whether the suffix is valid.

 

Java code:

package com.supermap.file;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.supermap.uitl.DateTimeUitl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpSession;

/** * File upload class **@author yushen
 *
 */
@Controller
public class UploadController {
	
	/** * Create log ** /
    private static final Log LOGGER = LogFactory.getLog(UploadController.class);
    
    // Get the base file service path address (incoming server ID, server file service path) 0 represents the first file server
    private static final String Basicspath = "/tem/Imagelserver/0/";	
    
    /** * File upload method **@param file
     * @param session
     * @return* /
    @RequestMapping("/2/Upload")
    @ResponseBody
    public String Upload(@RequestParam("file") MultipartFile file,HttpSession session) {
    	// Obtain the user ID through session to generate the user ID library path
        Integer user = (Integer) session.getAttribute("user");
        if(user == null) {
        	return "Upload failed, no user info!";
        }
        
    	// Log
    	LOGGER.info(new StringBuffer("User ID:"+user)+"Upload files!");
    	
    	// The file is judged to be empty
    	if (file.isEmpty()) {
            return "Upload failed, please select file";
        }
    	
    	// Get the original file name
        String fileOriginalName = file.getOriginalFilename();
        // Set the file prefix
        String fliePrefix = "";
        // Set the file suffix
        String fileSuffix = "";
        
        // Verify file name security
        if(fileOriginalName.indexOf(".") != -1) {// The judge contains the file with the ending character
        	// Only JPG and PNG files can be uploaded
        	if(fileOriginalName.split("\ \.") [1].equals("png") || fileOriginalName.split("\ \.") [1].equals("jpg")) {
        		fliePrefix = UUID.randomUUID().toString().replace("-"."");
        		fileSuffix = fileOriginalName.split("\ \.") [1];
        	} else {
        		return "Upload failed, upload file type is not PNG and JPG!"; }}// The system sets the path
        String newfilePath = DateTimeUitl.nowTimeA +"/" + user + "/" ;
        // Unique service address
        String newfilePathOnly = Basicspath +newfilePath;
        
        
        // Check whether the address exists
        File fileUIS = new File(newfilePathOnly);  
        if(! fileUIS.exists()){// Create a folder if no folder exists
        	fileUIS.mkdirs();  
        } 
        
        // Set the address to which the file is loaded
        File dest = new File(newfilePathOnly + fliePrefix + fileSuffix);
        try {
            file.transferTo(dest);
            LOGGER.info("File."+fliePrefix + fileSuffix+"Upload successful");
            return "Upload successful, file address:" + newfilePath + fliePrefix + fileSuffix;
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "Upload failed!"; }}Copy the code

The JSP code

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="http://localhost:8080/2/serviceUpload" 
    enctype="multipart/form-data"  method="POST" >Uploading files:<input type="file" name="file"/><br>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>
Copy the code

Pom.xml requires no special packages to be introduced