前言

近期在生产我的项目中遇到了文件上传与下载的问题,业务逻辑如下:

  • Angular从Java服务器中获取Excel模板,供用户下载
  • 用户填写实现后,通过Angular上传至服务器。

本文专一于探讨前后端拆散我的项目的文件下载的问题。

下载(Spring->Angular)

用户从服务器上获取Excel模板

文件传输格局

  • 模板文件放在Spring我的项目的Resources文件夹中
  • Spring应用File类型来发送文件
  • Angular应用Blob类型来接管文件

搁置文件

在Recourses目录搁置待传输的文件,相似这样:


示例文件 /upload/老师上传模板.xlsx

Spring Service

此处有一个坑,在我的项目的其它代码中发现了上传文件应用的是MultipartFile类型,天经地义的工作下载文件也是MultipartFile类型。
而后怎么使也不行,节约了好多工夫。
最初才晓得MultipartFileFile的继承树齐全不同,尽管有方法互相转化,但基本不通用。

UserService:

/** * 用户模板下载 * * @return 模板文件 */File download();

UserServiceImpl:

/**   * 用户模板下载 *  * @return File类型 模板文件   */public File download() {    // throw IOException 须要捕捉    try {        // 获取文件        File file = new ClassPathResource("upload/老师上传模板.xlsx").getFile();        // 返回文件        return (file);    } catch (Exception e) {        // 打印信息,返回null        logger.debug("模板下载失败");        return null;    }}

须要留神的是 ClassPathResource("upload/老师上传模板.xlsx").getFile(); 中的门路以Resources为根目录。

Spring Controller

UserCortroller:

@GetMapping("download")public File downloadTemplate() {    return this.userService.download();}

至尔后端编写结束,提供接口 user/download

Angular Service

向服务器发动申请。
UserService:

  /**   * 下载上传模板   */  public downloadUploadTemplate(): Observable<Blob> {    // const url = '/assets/files/userUploadTemplate.xlsx';    const url = 'api/user/download';    const httpHeader = new HttpHeaders().append(YunzhiInterceptor.DONT_INTERCEPT_HEADER_KEY, 'true');    return this.httpClient.get<Blob>(url, {headers: httpHeader, responseType: 'blob' as 'json'});  }

Angular Component

调用Service办法,而后通过FileSaver调用浏览器API保留文件。

UserComponent:

// 仅提供了性能代码,能够拼接到具体的办法中应用this.userService.downloadUploadTemplate()  .subscribe(data => {    // 获取文件后由FileSaver保留文件    FileSaver.saveAs(data, '老师上传模板.xlsx');  }, () => {    console.log('模板下载失败');  });

在Chrome中成果展现

总结

整个过程很容易了解,独自写前端或独自写后端都不难。
重点在于搞清楚通过HTTP传输的这个内容,具体是什么类型。

在Angular内置类中,Blob的正文这样写到:

A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

翻译过去就是:

不可变原始数据的相似文件的对象。blob示意不肯定是JavaScript原生格局的数据。文件接口基于Blob,继承Blob性能并将其扩大以反对用户零碎上的文件。

因而Angular的Blob能够作为后端Flie类型的接管类型。

版权申明

本文作者:河北工业大学梦云智开发团队 - 刘宇轩
新人经验不足,有倡议欢送交换,有谬误欢送轻喷