Angular 2:下载任何类型的文件

时间:2017-05-18 05:26:48

标签: java angular spring-boot

我想下载任何类型的文件,它可以是PDF,图像,Excel等,我想让它动态,我尝试了很多方法但失败了。发送给我application/octet-stream类型的服务器请帮帮我,下面是下载文件的代码:

注意:保存在文件系统中的文件,其唯一名称及其真实名称存储在数据库中,并与该唯一名称相关联。

服务器(Spring-Boot):

public class Media {
    private Integer id;
    private String uuid; // To store file on disk using unique name
    private String fileName;

    //Setter and getter
}

@GetMapping(value = "/{id}")
public ResponseEntity<?> get(@PathVariable("id") Integer id)
{
    Media media = mediaRepository.findOne(id);
    File file = new File("C:\\upload\\" + media.getUuid());
    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource byteArrayResource = new ByteArrayResource(Files.readAllBytes(path));


    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + media.getFileName());

    return ResponseEntity.ok()
                             .headers(headers)
                             .contentLength(file.length())
                             .contentType(MediaType.parseMediaType("application/octet-stream"))
                             .body(byteArrayResource);
}

Angular 2:

downloadAnyFile(id) {
  this.fileService.download(id).subscribe((res) => {
    var blob = new Blob([res._body], { type: res.headers.get("Content-Type") });
    var url= window.URL.createObjectURL(blob);
    window.open(url, "_blank");
  });
}

download(id) {
  return this.http.get(Constants.BASE_URL + this.context + id)
         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}

0 个答案:

没有答案