Take everyone to realize the vue2+Spring Boot2.7 file download function

The above guides you to implement the vue2+Spring Boot2.7 file upload function.
We have said that uploading and downloading in java Web are very common business logic.
We have also built an uploading environment
. In this article, we will talk about downloading
or creating it under the controller. A class called FileDownloadController
reference code is as follows

package com.example.javadom.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@RestController
public class FileDownloadController {
    
    
    @Value("${upload.path}") // 从配置文件中获取上传文件的路径
    private String uploadPath;

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) throws IOException {
    
    
        // 构建文件路径
        String filePath = uploadPath + File.separator + fileName;

        // 创建一个Resource对象,将文件内容加载到其中
        Resource resource = new UrlResource(Paths.get(filePath).toUri());

        // 设置响应头,告诉浏览器下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());

        // 返回响应实体,包含文件内容和响应头
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .contentType(MediaType.IMAGE_JPEG) // 设置文件类型为图片类型
                .body(resource);
    }
}

Accept a parameter fileName string type to execute which file in the directory needs to be downloaded,
and then start the project.
insert image description here
Then we open the vue project, add a download agent to vue.config.js
insert image description here
, and then rewrite the App.vue code as follows

<template>
  <div id="app">
    <h1>图片上传与下载</h1>
    <input type="file" @change="upload" />
    <img :src="url" />
    <button @click = "download">下载文件</button>
  </div>
</template>

<script>
import axios from 'axios';
export default {
      
      
  name: 'App',
  data() {
      
      
    return {
      
      
      url: "",
    }
  },
  methods: {
      
      
    download() {
      
      
      // 发送get请求
      axios.get("/download?fileName=html.jpg")
      .then(() => {
      
      
        console.log("下载成功");
        // 处理下载成功
      })
      .catch(error => {
      
      
        console.error(error);
        // 处理请求异常
      });
    },
    upload(event) {
      
      
      const file = event.target.files[0];
      this.url = URL.createObjectURL(file);
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', file);
      // 发送POST请求
      axios.post('/upload', formData)
      .then(response => {
      
      
        console.log(response.data);
        // 处理上传成功的逻辑
      })
      .catch(error => {
      
      
        console.error(error);
        // 处理上传失败的逻辑
      });
    }
  }
}
</script>

<style>
</style>

In fact, the main change is to add a button button
and then specify the click to trigger the download
to send a get request through the get function in axios, carry
the path parameter fileName, specify to download html.jpg
insert image description here
and then we run the project

When we click this download file, we will find that the request is indeed returned, but it is not downloaded locally in the browser.
insert image description here
We will change the download to this

download() {
    
    
  // 发送get请求
  axios.get("/download?fileName=html.jpg", {
    
     responseType: 'arraybuffer' })
    .then((response) => {
    
    
      // 创建一个blob对象
      const blob = new Blob([response.data], {
    
     type: response.headers['content-type'] });

      // 创建一个临时URL对象
      const url = window.URL.createObjectURL(blob);

      // 创建一个a标签并设置其href和download属性
      const link = document.createElement('a');
      link.href = url;
      link.download = "fileName.jpg";

      // 模拟点击下载链接
      link.click();

      // 释放临时URL对象
      window.URL.revokeObjectURL(url);
    })
    .catch(error => {
    
    
      console.error(error);
      // 处理请求异常
    });
},

Then we call download again
and click to download the file on the interface
insert image description here
, then we open the browser to download the content,
insert image description here
the file is already here
insert image description here
, then we open the local download folder,
insert image description here
we click to open it,
insert image description here
there is no problem

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132303914