SpringBoot implements file upload interface

Author platform:

| CSDN:blog.csdn.net/qq_41153943

| Nuggets: juejin.cn/user/651387…

| Zhihu: www.zhihu.com/people/1024…

| GitHub: github.com/JiangXia-10…

| WeChat public account: 1024 notes

This article is about 3845 words, and the estimated reading time is 10 minutes

foreword

File upload is a function that needs to be implemented in many business scenarios. Today, the interface for file upload is simply implemented based on the Springboot framework.

text

the code

It is actually very simple to use SpringBoot to implement the file upload interface.

1. First define a file upload service service and its implementation class:

public interface FileService {
    public FileReturn uploadFile(MultipartFile multipartFile);
}
复制代码
@Service
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Override
    public FileReturn uploadFile(MultipartFile multipartFile) {
//        文件保存路径
        String filePath = "F:\\filepath";
//        文件名
        String fileName = String.valueOf(System.currentTimeMillis());
        File file = new File(filePath +File.separator + fileName);
        FileOutputStream fileOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(file);
            IOUtils.copy(multipartFile.getInputStream(),fileOutputStream);
            System.out.println("===========file upload success=======");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
//                关闭
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("文件关闭错误",e);
            }
        }

        return new FileReturn<>(1,"文件上传成功",file);
    }
}

复制代码

2. Define an entity class that uniformly returns results:

public class FileReturn<T> implements Serializable {
    private static final long serialVersionUID = -1959544190118740608L;
    private int resultCode;
    private String msg;
    private T data;

    public FileReturn() {

    }

    public FileReturn(int resultCode, String msg, T data) {
        this.resultCode = resultCode;
        this.msg = msg;
        this.data = data;
    }

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "FileReturn{" +
                "resultCode=" + resultCode +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
复制代码

3. Define another tool class to process the returned results:

public class ReturnValue<T> implements Serializable {
    private static final long serialVersionUID = -1959544190118740608L;
    private int ret;
    private String msg;
    private T data;

    public ReturnValue() {
        this.ret = 0;
        this.msg = "";
        this.data = null;
    }

    public ReturnValue(int retCode, String msg, T data) {
        this.ret = 0;
        this.msg = "";
        this.data = null;
        this.ret = retCode;
        this.data = data;
        this.msg = msg;
    }

    public ReturnValue(int retCode, String msg) {
        this.ret = 0;
        this.msg = "";
        this.data = null;
        this.ret = retCode;
        this.msg = msg;
    }

    public ReturnValue(ReturnCodeAndMsgEnum codeAndMsg) {
        this(codeAndMsg.getCode(), codeAndMsg.getMsg(), null);
    }

    public ReturnValue(ReturnCodeAndMsgEnum codeAndMsg, T data) {
        this(codeAndMsg.getCode(), codeAndMsg.getMsg(), data);
    }

    public int getRet() {
        return this.ret;
    }

    public void setRet(int ret) {
        this.ret = ret;
    }

    public String getMsg() {
        return this.msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ReturnValue{" +
                "ret=" + ret +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
复制代码

4. Finally, implement a Controller to handle file upload requests:

@RestController
@RequestMapping(value="/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public FileReturn uploadFile(@RequestParam("uploadFile") MultipartFile multipartFile){
        return fileService.uploadFile(multipartFile);
    }
}
复制代码
5、可以在application.yml中加入以下配置,限制大小:
复制代码
spring:
  servlet:
    multipart:
#      单个文件最大限制 类型是datasize,单位kb
      max-file-size: 1024
#      单次请求最大限制
      max-request-size: 2048
复制代码

test

Here, the postman test software is used for testing, and the request address is as follows:

http://localhost:8081/share/file/upload
复制代码

Select file as the parameter type, and the specific request is as follows:

picture

Select a file in zip format, then click send, and the request is successful, and the returned data is as follows:

picture

Then the f disk, the file under the file folder has been uploaded, and the file name is the timestamp:

picture

Summarize

The above is how to use springboot to develop a file upload interface. In fact, it has nothing to do with springboot. It is to use it for interface development. Here is just a simple core content, which can be expanded and extended according to your actual business and needs.

If you have any questions or mistakes, welcome to communicate, discuss and learn together!

The source code of this project is at:

github.com/JiangXia-10…

Welcome to download, Star!

related suggestion

Guess you like

Origin blog.csdn.net/qq_41153943/article/details/124878844