用Django和Angular2下载Excel文件

我有一个项目,我保存在SMB文件夹中的文件,并使用Django的背面和Angular 2的正面。 我已成功地设法下载.csv文件,但下载.xls文件时,它已损坏。 文件中的行如下所示:

pipe理员 – 格里沙姆
巴== o'x <* 8X @“1Arial1Arial1Arial1Arial1?Arial1Arial1 $ Arial1Arial1Calibri1

这是我的views.py文件:

'''Download file''' def get(self, request, file_name): bicloudreposervice = BiCloudRepoService() file_obj = bicloudreposervice.get_user_file(request.user.email, file_name) file_path = file_obj.name with open(file_path, 'rb') as tmp: if 'xls' in file_name: resp = HttpResponse(tmp, content_type='application/vnd.ms-excel;charset=UTF-8') else: resp = HttpResponse(tmp, content_type='application/text;charset=UTF-8') resp['Content-Disposition'] = "attachment; filename=%s" % file_name self.logger.debug('Downloading file') return resp 

打字稿中的服务文件中的相关function如下所示:

  downloadFile(fileName: string){ let headers = this.headers; let options = new RequestOptions({ headers: headers }); return this.http.get(this.connectorsUrl+'download-file/' + fileName + '/', options) .map(res => res) .catch(this.utils.handleError); } 

和组件文件:

  import * as FileSaver from "file-saver"; ... downloadFile(name){ this.connectorsService.downloadFile(name).subscribe( res => {this.successDownloadFile(res, name);}, error => this.errorMessage = <any>error, ()=> {}); } successDownloadFile(res: any, name: String){ this.showLoader = false; let blob; blob = new Blob([res._body], {type: 'application/vnd.ms-excel'}); FileSaver.saveAs(blob, name.toString()); } 

相应的html文件:

 ... <div (click)="downloadFile(file.name)"> <i class="material-icons">file_download</i> </div> ... 

我使用外部库FileSaver,但我也尝试从Blob创build一个URL对象,并在Angular中创buildwindow.open,但该文件看起来仍然相同。 我已经在views.py中尝试了content_type='application/vnd.ms-excel;charset=UTF-8'并且{type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}); 当在Angular中创buildBlob时。

我能做什么错了? 也许我应该在Django中以不同的方式处理文件? 预先感谢您的帮助。