带有 Angular 6 和 API 驱动器的 dowload 文件



当我尝试下载一些文件时,我遇到了这个问题,唯一有效的文件是.txt 其他文件已损坏。

async downloadFromDrive(accountId: string, fileName: string, partNumber): Promise<boolean> {
return new Promise((resolve,reject)=>{

gapi.load('client:auth2', () => {
return gapi.client.init({
apiKey: this.API_KEY,
clientId: this.CLIENT_ID,
discoveryDocs: this.DISCOVERY_DOCS,
scope: this.SCOPES
}).then(() => {
this.googleAuth = gapi.auth2.getAuthInstance();
this.googleAuth.signIn().then(() => {
gapi.client.setToken({access_token: this.cookieService.get(accountId)});
gapi.client.drive.files.get({
fileId: fileName,
alt: 'media',
}).then(res => {
let blob = new Blob([res.body], {type: 'application/pdf'
});
this.sortedFiles[partNumber] = blob;
console.log('res-body',res.body)
resolve()
}) 
})
});` });

.LOG:

âãÏ 3 0 obj <>流 x í]M E }¿DÁÿ ú ² ÀMÜ»0{Á¬ ̧r ÉF!d50' !à a ! h$'ç9ìñæþê~ýõªzfÌ= í{ÕU·>î©[ ]Õ= D" H$ D"q 8|þ÷ý'/

您需要将其添加到您的请求中

responseType: 'arraybuffer'

像这样:

...
this.http.get(`${url}`,{
responseType: 'arraybuffer', headers:headers}).subscribe(response => 
...

我尝试添加 responseType,但文件总是损坏:

async downloadFromDrive(accountId: string, fileName: string, partNumber): Promise<boolean> {
return new Promise((resolve,reject)=>{
gapi.load('client:auth2', () => {
return gapi.client.init({
apiKey: this.API_KEY,
clientId: this.CLIENT_ID,
discoveryDocs: this.DISCOVERY_DOCS,
scope: this.SCOPES
}).then(() => {
this.googleAuth = gapi.auth2.getAuthInstance();
this.googleAuth.signIn().then(() => {
gapi.client.setToken({access_token: this.cookieService.get(accountId)});
gapi.client.drive.files.get({
fileId: fileName,
/* alt: 'media'*/
alt: 'media',

/* mimeType:'image/jpeg'*/
}).then(res => {
let header= new HttpHeaders({
'Authorization' : 'Bearer ' +  this.cookieService.get(accountId),
'responseType' : 'arraybuffer'
});
this.http.get(res.result.webContentLink, { responseType: 'arraybuffer', headers: header} ).subscribe(res => {console.log(res);
/*resolve()*/});
console.log('download',res)
let blob: Blob = new Blob([res.body],{ type:'mimeType'})
this.sortedFiles[partNumber] = blob;
console.log('res-body')
resolve()

最新更新