Files is used to upload and download files and pictures with front-end and back-end separation

Recently found a very useful way to upload and download files, so today I will bring you, hoping to help you.
First of all, the project is based on SpringBoot development, and if you use Spring, it won't affect either.
Functional demonstration:


Bullshit goes straight to the code

  • 1. Create a StoreService to upload and download files
@Service
@Slf4j
public class StoreService {

    //Classes used to retrieve attributes in configuration files
    @Autowired
    private Environment env;

    //File save path
    private String fileStorePath;

    //For locks
    private final Object createFileLock = new Object();

    /**
     * Save the file and return to file key
     */
    public String upload(MultipartFile file) {
        return storeFile(file);
    }

    public void download(String key, HttpServletResponse response) {
        Assert.hasText(key, "Invalid key");
        try {
            Files.copy(getFile(key), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Download Send Error");
        } catch (StringIndexOutOfBoundsException e) {
            throw new IllegalArgumentException("Invalid key!");
        }
    }


    @PostConstruct
    private void setFileStorePath() {
        String property = env.getProperty("file.store.path");
        Assert.notNull(property, "must set fileStorePath");
        log.info("path: {}", property);
        fileStorePath = property;
    }

    private boolean checkPathConflict(Path path) {
        return Files.exists(path);
    }


    //Create a save path for the image
    private Path name2Path(String fileName) {
        //16 * 16 * (16*16)
        return Paths.get(fileStorePath, fileName.substring(0, 2), fileName.substring(2, 4), fileName);
    }

    //Save File Implementation
    private String storeFile(MultipartFile file) {
        synchronized (createFileLock) {
            //File save path
            Path path;
            //Picture name
            String fileName;
            do {
                //Image Name Assignment
                fileName = UUID.randomUUID().toString();
                //Save path assignment
                path = name2Path(fileName);
                //The loop condition is if the file address does not exist
            } while (checkPathConflict(path));
            try {
                //create folder
                Files.createDirectories(path.getParent());
                //Copy the file to the specified folder
                Files.copy(file.getInputStream(), path);
                return fileName;
            } catch (IOException e) {
                log.info("io err", e);
                throw new IllegalArgumentException("File upload failed");
            }
        }
    }

    //Now picture implementation
    private Path getFile(String fileName) {
        //Get the file save path
        Path path = name2Path(fileName);
        Assert.isTrue(Files.exists(path), "Invalid Filename " + fileName);
        return path;
    }


}
  • 2. Create a Controller to provide access
@Slf4j
@RestController
public class FileController {

    @Autowired
    StoreService storeService;

    @PostMapping(value = "/file/upload")
    public Object upload(MultipartFile multipartFile){
        return storeService.upload(multipartFile);
    }

    @PostMapping(value = "/file/download")
    public Object download(String key, HttpServletResponse response){
        storeService.download(key,response);
        return key+"Picture Return Successful";
    }
}

3. Add the configuration of the file save address to the configuration file

file.store.path=E:\\projectFiles\\market

Here are a few more folders and a file under my E: project Files market folder. When we call the download interface, we just need to input a string of strings that we returned when uploading to download, and then we can download the picture. As for the return format, we need to set it by ourselves. I have set the unified return format here in other places.

It's over here. Thank you for watching.

Tags: SpringBoot Spring

Posted on Mon, 07 Oct 2019 22:29:57 -0700 by adavis