vue前端下载文件,java后端

vue前端

html 复制代码
<template>
  <div>
    <button @click="downloadFile">Download File</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async downloadFile() {
      try {
        const response = await axios.get('http://your-backend-url/download', {
          responseType: 'blob' // 告诉axios响应的数据类型为Blob
        });
        const blob = new Blob([response.data], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'filename.ext'); // 设置下载文件的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('Error downloading file:', error);
      }
    }
  }
}
</script>

java后端代码

java 复制代码
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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/download")
public class FileDownloadController {

    @GetMapping
    public ResponseEntity<Resource> downloadFile() {
        // 指定要下载的文件路径
        String filePath = "/path/to/your/file.ext";
        Path path = Paths.get(filePath);
        Resource resource;
        String contentType;
        try {
            // 从文件路径创建一个资源对象
            resource = new UrlResource(path.toUri());
            // 根据文件扩展名动态设置 Content-Type
           contentType = determineContentType(resource.getFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }

        // 检查资源是否存在并且可读
        if (!resource.exists() || !resource.isReadable()) {
            return ResponseEntity.notFound().build();
        }

        // 尝试下载文件
        try {
           
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))// 设置响应内容类型为流数据
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") // 设置下载文件的文件名
                    .body(resource); // 返回资源对象
        } catch (Exception e) {
            e.printStackTrace();
            // 如果下载失败,
            //return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载文件失败,请稍后重试。");
        }
    }
	// 根据文件扩展名返回对应的 Content-Type
	private String determineContentType(String filename) {
	    String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
	    switch (extension) {
	        case "pdf":
	            return "application/pdf";
	        case "txt":
	            return "text/plain";
	        case "doc":
	        case "docx":
	            return "application/msword";
	        case "xls":
	        case "xlsx":
	            return "application/vnd.ms-excel";
	        // 其他文件类型...
	        default:
	            return "application/octet-stream"; // 默认为二进制数据流
	    }
	}
}
相关推荐
fishmemory7sec3 分钟前
Electron 主进程与渲染进程、预加载preload.js
前端·javascript·electron
小叶学C++4 分钟前
【C++】类与对象(下)
java·开发语言·c++
fishmemory7sec6 分钟前
Electron 使⽤ electron-builder 打包应用
前端·javascript·electron
2401_854391088 分钟前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
Cikiss16 分钟前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务
wxin_VXbishe17 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
Cikiss18 分钟前
微服务实战——平台属性
java·数据库·后端·微服务
无敌の星仔27 分钟前
一个月学会Java 第2天 认识类与对象
java·开发语言
OEC小胖胖31 分钟前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web
工业互联网专业36 分钟前
毕业设计选题:基于ssm+vue+uniapp的校园水电费管理小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计