This is the second day of my participation in Gwen Challenge

preface

The project I’m working on needs a file upload interface. In the process of writing, encountered many pits, here to share

The environment

My development environment

| SpringBoot |    2.4. 5   |
| Linux      | Centos 7.5 |
| Java       |     1.8    |
Copy the code

Lu code

Controller

Note that multipart/form-data is used to receive data

@PostMapping(value="/upload",consumes = "multipart/*",headers = "content-type=multipart/form-data")
@APIoperation (value = "Consumes = "multipart/form-data", Produces = "multipart/form-data")
@apiIMPLICITParam (name = "file", value = "file", dataTypeClass = multipartfile.class)
public ResultBean<Object> upload( @ApiParam(name = "file",value = "file", required = true) MultipartFile file) {
    // Check whether there are files
    if (file.isEmpty()) {
        return ResultBean.error(ResultEnum.NOT_FILE);
    }
    // Get the file name
    String originalFilename = file.getOriginalFilename();
    // Get the file suffix
    String suffix = originalFilename.substring(originalFilename.lastIndexOf('. ') + 1);
    // Check whether the file type can be received
    // public final static String avatarFileSuffix = ".jpg.jpeg.png";
    if(! FileSuffix.avatarFileSuffix.contains(suffix)) {return ResultBean.error(ResultEnum.FILE_TYPE_ERROR);
    }
    // Use the uuid as the new file name
    String fileName = UUID.randomUUID() +"."+suffix;

    try {
        // Get the static resource path
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(! path.exists()){ path=new File("");
        }
        // Set the storage path
        File upload=new File(path.getAbsolutePath(),"static/images/upload/"+fileName);
        // Create a directory if it does not exist
        if(! upload.exists()){ upload.mkdirs(); }/ / write
        file.transferTo(upload);
        return ResultBean.success("/images/upload/"+fileName);
    } catch (IOException e) {
        e.printStackTrace();
        returnResultBean.error(ResultEnum.UPLOAD_ERROR); }}Copy the code

OK upload interface written, local test

The Swagger3 notation used here cannot upload files directly in swagger-UI

Write a simple HTML file to test it out

<! DOCTYPEhtml>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>Single file upload</title>
</head>
<body>
<form method="post" action="http://localhost:8090/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>
Copy the code

Not bad, enough

Select file, submit OK no problem. Access was no problem

Then upload to the server to run upload OK, visit…… Inaccessible – The interface page cannot be found. We’ll solve that later

Let’s start with the pits that the upload interface encounters

pit

Written before a version of the report the results of using the relative path of the Java exception. IO. FileNotFoundException

You need to use absolute paths

Caused by: java.io.FileNotFoundException: /tmp/tomcat8223985333111777969.80./work/Tomcat/localhost/ROOT/file:/project/xxx-0.01.-SNAPSHOT.jar!/BOOT-INF/classes!/static/images/upload/655acb70-c979-4ba4-b421-ca1c0d18bf1a.png (No such file or directory)

Copy the code

Configuring Static Resources

Note that Linux does not unzip.jar files, which do not exist locally in classes, and are stored in the same directory as the jar package

This leads to the second problem, although the file is uploaded to the Linux server, it cannot be accessed

We need to configure the static resource path static-locations

Notice the last file: / root/public/static/behind the file is the location of the file upload after storage

server:
  resource:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/root/public/static/

Copy the code