java - 无法下载文件 : cannot be resolved to URL because it does not exist with Spring

标签 java spring angular spring-boot angular6

我想使用 Angular 6 代码实现文件下载:

休息 API:

private static final Logger LOG = LoggerFactory.getLogger(DownloadsController.class);

private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";

@GetMapping("export")
public ResponseEntity<InputStreamResource> export() throws IOException {
    ClassPathResource pdfFile = new ClassPathResource(EXTERNAL_FILE_PATH);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
            .contentType(MediaType.parseMediaType("application/pdf"))
            .body(new InputStreamResource(pdfFile.getInputStream()));
}

服务:

import {Component, OnInit} from '@angular/core';
import {DownloadService} from "../service/download.service";
import {ActivatedRoute, Router} from "@angular/router";
import {flatMap} from "rxjs/internal/operators";
import {of} from "rxjs/index";
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-download',
  templateUrl: './download.component.html',
  styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {

  constructor(private downloadService: DownloadService,
              private router: Router,
              private route: ActivatedRoute) {
  }

  ngOnInit() {   
  }

  export() {               
    this.downloadService.downloadPDF().subscribe(res => {
      const fileURL = URL.createObjectURL(res);
      window.open(fileURL, '_blank');
    });         
  } 
}

组件:

import {Component, OnInit} from '@angular/core';
import {DownloadService} from "../service/download.service";
import {ActivatedRoute, Router} from "@angular/router";
import {flatMap} from "rxjs/internal/operators";
import {of} from "rxjs/index";
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-download',
  templateUrl: './download.component.html',
  styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {

  constructor(private downloadService: DownloadService,
              private router: Router,
              private route: ActivatedRoute) {
  }

  ngOnInit() {   
  }

  export() {               
    this.downloadService.downloadPDF().subscribe(res => {
      const fileURL = URL.createObjectURL(res);
      window.open(fileURL, '_blank');
    });         
  } 
}

当我点击下载按钮时,我得到这个 Spring 错误:

15:28:02,819 ERROR [org.springframework.boot.web.servlet.support.ErrorPageFilter] (default task-1) Forwarding to error page from request [/downloads/export] due to exception [class path resource [Users/test/Documents/blacklist_api.pdf] cannot be resolved to URL because it does not exist]: java.io.FileNotFoundException: class path resource [Users/test/Documents/blacklist_api.pdf] cannot be resolved to URL because it does not exist
    at deployment.test_admin.war//org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195)

该文件存在于目录中,但看起来它位于 war 包之外,而且我无法访问它。有什么方法可以配置 Java 来访问它并下载它吗?

最佳答案

由于您使用的是 ClasspathResource,因此您只能获取类路径“”的文件。

如果您的文件在类路径之外,您将无法通过这种方式获取它。

private static final Logger LOG = LoggerFactory.getLogger(DownloadsController.class);

private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";

@GetMapping("export")
public ResponseEntity<InputStreamResource> export() throws IOException {
    File pdfFile = Paths.get(EXTERNAL_FILE_PATH).toFile();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    return ResponseEntity.ok().headers(headers).contentLength(pdfFile.length())
            .contentType(MediaType.parseMediaType("application/pdf"))
            .body(new FileInputStream(pdfFile));
}

我改变了你获取文件的方式,一个文件而不是一个 ClassPathResource。

我临时修改了那段代码,如有错误请见谅。希望对你有帮助

关于java - 无法下载文件 : cannot be resolved to URL because it does not exist with Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239615/

相关文章:

java - Spring 安全: How to set a custom PortMapper?

angularjs - Webpack - Typescript 和 Babel "Module build failed: SyntaxError"

javascript - 找不到模块 : Error: Can't resolve 'X\node_modules\ng-zorro-antd\src\ng-zorro-antd.less'

java - 自动组织 JUnit 测试

java - 通过字符串格式的 IP 地址递增

java - 添加依赖项和库 .jar 后无法解析 json import Intellij

java - HTTP 状态 404 - 在创建 Spring Boot 应用程序时未找到

java - 解析文件并按属性对行进行排序

java - 使用 TaskExecutor 提交后`TransactionSynchronizationManager` 内的事务

angular - 解析器如何与 SSR 和 Angular Universal 配合使用