Spring Boot + Vue + Element-UI 实现文件下载

实现效果:点击链接,下载对应文件

Spring Boot + Vue + Element-UI 实现文件下载_第1张图片

后端接口:

import com.example.admin.entity.FileEntity;
import com.example.admin.service.FileService;
import com.example.admin.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

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

    @Autowired
    private FileService fileService;

    // 根据文件id查询文件信息
    @GetMapping("/getFile")
    public Result getFile(String fid) {
        return fileService.getFileById(fid);
    }

    // 文件下载
    @GetMapping("/download")
    public void fileDownload(String fid, HttpServletResponse response) throws IOException {
        FileEntity fileEntity = fileService.getFileById(fid).getData();
        String fname = fileEntity.getFname();
        String path = fileEntity.getPath();
        File file = new File(path);
        FileInputStream is = new FileInputStream(file);
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "UTF-8"));
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

}

前端代码:


  
/* 下载文件 */
async download(fid) {
  try {
    const response = await this.$axios.get("/api/file/download", {
      params: {
        fid: fid,
      },
      responseType: "arraybuffer",
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    // 获取文件信息
    const fileInfoResponse = await this.$axios.get("/api/file/getFile", {
      params: {
        fid: fid,
      },
    });
    const fname = fileInfoResponse.data.data.fname;
    link.setAttribute("download", `${fname}`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error("Download error:", error);
  }
},

你可能感兴趣的:(前端,spring,boot,vue.js,ui)