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"; // 默认为二进制数据流
	    }
	}
}
相关推荐
资生算法程序员_畅想家_剑魔几秒前
Java常见技术分享-13-多线程安全-锁机制-底层核心实现机制
java·开发语言
萤丰信息3 分钟前
数智重构生态:智慧园区引领城市高质量发展新范式
java·大数据·人工智能·安全·智慧城市
用户952081611793 分钟前
百度地图MapVThree Editor:地图编辑
前端
悟空码字9 分钟前
MySQL分库分表,从“一室一厅”到“豪华别墅区”的数据库升级之旅
java·后端·mysql
Lisonseekpan10 分钟前
RBAC 基于角色的访问控制模型详解与实践指南
java·服务器·网络·后端·spring·log4j
奔跑的小十一20 分钟前
ShardingSphere-JDBC 开发手册
java·数据库
lkbhua莱克瓦2421 分钟前
基础-MySQL概述
java·开发语言·数据库·笔记·mysql
程序员龙语22 分钟前
CSS 文本样式与阴影属性
前端·css
月明长歌24 分钟前
【码道初阶】Leetcode136:只出现一次的数字:异或一把梭 vs HashMap 计数(两种解法完整复盘)
java·数据结构·算法·leetcode·哈希算法
Swift社区30 分钟前
LeetCode 456 - 132 模式
java·算法·leetcode