Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从Java后端下载带有Angular前端的文件_Javascript_Java_Spring_Angular_Angular5 - Fatal编程技术网

Javascript 从Java后端下载带有Angular前端的文件

Javascript 从Java后端下载带有Angular前端的文件,javascript,java,spring,angular,angular5,Javascript,Java,Spring,Angular,Angular5,我不知道如何使用Angular从API下载文件。我从后端发送了一个Blob,但我认为我没有正确地转换它,因为它会给我一个序列化错误。然而,bytearray确实给了我它的内容,但不是作为下载 这是我的Java代码: @GetMapping("{id}") public byte[] getExambyId(@PathVariable int id) { Exam exam = new Exam(); byte[] file; try { exam = ex

我不知道如何使用Angular从API下载文件。我从后端发送了一个Blob,但我认为我没有正确地转换它,因为它会给我一个序列化错误。然而,bytearray确实给了我它的内容,但不是作为下载

这是我的Java代码:

@GetMapping("{id}")
public byte[] getExambyId(@PathVariable int id) {
    Exam exam = new Exam();
    byte[] file;
    try {
        exam = examRepository.findById(id).get();
        file = IOUtils.toByteArray(new FileInputStream(storageService.load(exam.getSkelet()).toFile()));
    } catch (NoSuchElementException e) {
        log.error("Exam with id: " + id + " not found.", this.getClass());
        return null;
    } catch (StorageFileNotFoundException e) {
        log.error("Cannot find examfile: " + exam.getSkelet() + ".", this.getClass());
        return null;
    } catch (FileNotFoundException e) {
        log.error("Cannot find file with filestream: " + exam.getSkelet() + ".", this.getClass());
        return null;
    } catch (IOException e) {
        log.error("IoException on: " + exam.getSkelet() + ".", this.getClass());
        return null;
    }
    return file;
}
这是我在前端的服务:

getExamSkeletById(id) {
  window.open(APIURL + '/' + id);
}

我不使用Java,因此无法评论来自服务器的数据是否正确。但在我的Angular项目中,我使用npm的“文件保护程序”库来触发保存从服务器发送的PDF。然后在我的角度代码中,有一个效果是:

import * as FileSaver from 'file-saver';

downloadPDF() {
    this.http.get("api/endpoint/address", {withCredentials: true, responseType: "blob"}).subscribe(r => {
      var blob = r;
      FileSaver.saveAs(blob, "Filename.pdf");
    });
}

http是指注入组件构造函数中的HttpClient。

很高兴它能工作。作为一个小的跟进,关于下载不起作用的原因,有一个猜测可能是您丢失了从服务器发送的一些头以及您的字节数组。我知道有一些东西,如内容配置和内容类型标题,可以帮助告诉浏览器数据是什么。此外,内容长度还可用于告诉浏览器文件有多大,以便您可以获取下载进度指示器。