SpringBoot implements local file storage and preview

I. Introduction

If you use local storage to store file resources, the core implementation process:

  • Upload file, save file (local disk)
  • Return the file HTTP access server path to the front end for effect display

2. Reserves

The purpose of receiving and uploading on the server side is to provide file access services. For SpringBoot, it provides good support for static resource access. Using the basic default configuration provided by it can meet the development needs, and at the same time, it supports developers. Define configuration.

SpringBoot maps / all accesses to the following directories by default: **

  • classpath:/META-INF/resources
  • classpath:/static
  • classpath:/public
  • classpath:/resources

Create three new folders, public, resources, and static under src/main/resources, and put in three pictures x.png, xx.png, and xxx.png respectively, as follows:

 After starting the project, visit:

http://localhost:9999/x.png
http://localhost:9999/xx.png
http://localhost:9999/xxx.png

Returns the image resource normally.

Note that by default, SpringBoot will find out whether there are corresponding resources from public, resources, and static one by one, and return them directly if there are.

It can be seen that the static resources here are all under the classpath. Then there is a problem:

  • Application file resources cannot be stored separately from project code
  • It is difficult to package the project. When more and more files are uploaded, the packaged jar of the project is getting bigger and bigger
  • Code and file data cannot be stored separately, which means that the backup of file data will become complicated

3. Program

SpringBoot provides us with spring.resources.static-locations to configure the location of custom static files:

spring:
    web:
        resources:
          static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${demo.web.upload-path}

demo:
  web:
    upload-path: D:/data/
  • Configure demo.web.upload-path as a static resource path separated from the project code, that is: file upload save root path
  • Configure spring.web.resources.static-locations In addition to bringing the default static resource path of SpringBoot, add file:${demo.web.upload-path} to point to the external file resource upload path, that is: under this path Static resources can directly provide HTTP access services externally

Four: Java Code

public String upload(MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            throw new BizException("参数为空");
        }
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 例如:/2022/02/22/df9a66f1-760b-4f95-9faf-b5a216966718.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名, 避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            // 例如:http://localhost:9999/2022/02/22/df9a66f1-760b-4f95-9faf-b5a216966718.png
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath() + "/" + format + newName;

            return filePath;
        } catch (IOException e) {
            throw new BizException("系统错误");
        }

    }

5. Simulation file

Put this upload.html file in the classpath:public directory to provide external access. as follows:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择上传文件">
    <input type="submit" value="保存">
</form>
</body>
</html>

Access the test, click "Choose File", then "Save":

 The file is saved to the resource directory specified by demo.web.upload-path on the server

 The browser-side response results are as follows, returning a file HTTP access path:

http://localhost:9999/2022/02/22/df9a66f1-760b-4f95-9faf-b5a216966718.png

Using this HTTP access path, the access effect on the browser side is as follows. It proves that our file has been successfully uploaded to the server, and if we need to access the picture in the future, we can just use this HTTP URL! ! !

 

Guess you like

Origin blog.csdn.net/m0_60252632/article/details/126061734