[springboot project development] file upload and download

Table of contents

General introduction

File Upload

introduce

Front-end requirements for file uploads

Front-end code for file upload

Backend requirements for file uploads

Backend code for file upload

Download Document

introduce

Front-end requirements

front-end code

Backend requirements

backend code


General introduction

The function of uploading and downloading files is a relatively common business requirement in the project development process. The visual effect we are displayed on the client is as follows: add the local file to the specific location of the browser under the prompt of the front-end page of the project, and then browse The device directly echoes this picture, and the specific effect is as follows:

 However, the uploading file under our visual effect is not a single file uploading process: it is composed of two parts: uploading and downloading the file, that is, the file is uploaded locally from the client to the server and the server echoes the file in the browser (download to the server), and then we will introduce the two processes in detail

File Upload

introduce

File upload, also known as upload, refers to the process of uploading local pictures, videos, audio and other files to the server, which can be browsed or downloaded by other users. File upload is widely used in projects. We often send Weibo, post Wechat Moments all use the file upload function.

Front-end requirements for file uploads

 However, in the actual development process, the design of this part of the front-end page is usually packaged with components. For example, element-ui is used to optimize the design of the upload component page based on the completion of function realization. (The bottom layer still uses the post form to send requests)

as follows:

 

Front-end code for file upload

The code of the element-ui that implements the upload function is as follows:
 

 <div class="addBrand-container" id="food-add-app">
    <div class="container">
        <el-upload class="avatar-uploader"
                action="/common/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeUpload"
                ref="upload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
  </div>

Backend requirements for file uploads

To receive the files uploaded by the client page, the server usually uses two components of Apache:

  • commons-fileupload
  • commons-io

The Spring framework encapsulates the file upload in the spring-web package, which greatly simplifies the server code. We only need to declare a parameter of type MultipartFile in the Controller method to receive the uploaded file, for example:

 

Regarding the back-end implementation logic for file uploads, the general implementation ideas are as follows:

1. First use the formal parameters of the MultipartFile class to receive the file from the client. We need to pay attention to: after the MultipartFile class object receives the file, it will temporarily store the file and generate a temporary file. When we end the transmission After the process, no matter whether the file is dumped or not, this temporary file will disappear,

2. Therefore, our next step is to transfer this temporary file, because the file name problem will inevitably be involved in the file transfer process. If the file name of the original file is used, there may be a problem of duplicate file names, so Generate a new random file name on the basis of the original, and dump it with the new file name,

2. At the end, we must remember to return the newly generated file name, because upload just uploads the file to the server, and later involves a work of echoing the file on the browser, which needs to be used

We give the back-end code implementation of file upload:

Backend code for file upload

We read the file save path from the configuration file by using the @Value annotation:
 

 @Value("${reggie.path}")
    private String path;
reggie:
  path: D:\img\
 @PostMapping("/upload")
    public R<String>upload(MultipartFile file){
        log.info(file.toString());
        //获取原始文件名,提取JPG
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机文件名
        String random=UUID.randomUUID().toString();
        //获取新名称
        String fileName=random+suffix;
        //创建新名称
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //进行转存
        try {
            log.info("文件路径为"+path+fileName);
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

notes : Regarding the object name of the MultipartFile class: this object name must be consistent with the object name sent from the front end, that is to say, the interaction between the front and back ends is matched by the object name. If the object names are inconsistent, the MultipartFile file object passed to the back end is An empty object, the specific demonstration is as follows:

Download Document

introduce

File download, also known as download, refers to the process of transferring files from the server to the local computer

There are usually two forms of file download through the browser:

  • Download as an attachment, pop up a save dialog box, and save the file to the specified disk directory
  • open directly in the browser

Downloading files through a browser is essentially the process in which the server associates the file to the browser in the form of a stream

Front-end requirements

To realize the full image echo function, the upload function must be completed before downloading, and the file name of the file to be echoed must be obtained, so the requirement of the front end is to send a new request to the server according to the file name returned by the upload response File information, so as to echo the photo information, the code example and the specific request url are as follows

Code example:

url display: We can find that the download url contains the file name of the specific picture

front-end code

The specific front-end code is as follows:

  methods: {
          handleAvatarSuccess (response, file, fileList) {
              this.imageUrl = `/common/download?name=${response.data}`
          },
          beforeUpload (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          }
        }

Backend requirements

The back end receives the file name from the front end, creates a FileInputStream object according to the file path and file name, uses the response object to create a ServletOutputStream object, reads data from the FileInputStream file and writes it into the ServletOutputStream object through an array, and finally remember to close the stream resource

backend code

 The backend code is as follows:

 

 @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        //输入流,通过提供指定位置去读取数据
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));
            //输出流,通过读取到的数据输出到浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            //将数据通过byte字符数组进行读取
            int len=0;
            byte[]bytes=new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                //刷新
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

Guess you like

Origin blog.csdn.net/m0_65431718/article/details/131062841