帮助:Ionic /我正在尝试将文件上传到 firebase,但我无法阅读文件帮助 enter image description here
的内容import { Component } from '@angular/core';
import { File} from '@ionic-native/file/ngx';
import { FileChooser } from '@ionic-native/file-chooser/ngx';
import { FilePath } from '@ionic-native/file-path/ngx';
import { FireBaseService } from 'src/app/services/firebase-service.service';
import { Plugins, FilesystemDirectory, FilesystemEncoding } from '@capacitor/core';
const { Filesystem } = Plugins;
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
fileforSending ;
fileUri :string;
filePath :string;
fileName :string;
fileType :string;
entry;
constructor(
private fireService:FireBaseService,
private fileChooser:FileChooser,
private file :File,
private pathConverter :FilePath) {
}
choose(){
this.fileChooser.open()
.then(uri => {
//getting URI of a choosen file
this.fileUri = uri;
return this.file.resolveLocalFilesystemUrl(this.fileUri);
}).then(fileEntry => {
this.entry = fileEntry;
this.entry.file((arg) => {
//getting mime type of a file
this.fileType = arg.type;
})
}).then(() => {
return this.pathConverter.resolveNativePath(this.fileUri)
}).then((filePath) => {
//converting file URI to normal file PATH & file NAME
this.filePath = filePath.substring(0, filePath.lastIndexOf('/'));
this.fileName = filePath.substring(filePath.lastIndexOf('/'), filePath.length).replace("/", "");
}).then(async () => {
try {
const buffer = await this.file.readAsArrayBuffer(this.filePath, this.fileName);
await this.fireService.uploadFileToStorage(buffer, this.fileType, this.fileName);
} catch (error) {
alert(`Buffering failed ${JSON.stringify(error)}`)
} finally {
alert('finally');
}
}).catch(err => {console.log('error: ', err) });
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
从'@angular/core'导入{可注射}; 从“@angular/fire/database”导入{AngularFireDatabase};
从“@angular/fire/storage”导入{AngularFireStorage};
@Injectable({ 提供在:'根' }) 导出类 FireBaseService {
constructor(private af: AngularFireStorage){}
async uploadFileToStorage(file, type, name) {
const randomId = Math.random()
.toString(36)
.substring(2, 8);
let oMyBlob = new Blob([file], {type : type})
const uploadTask = this.af.upload(
`files/${new Date().getTime()}_${randomId}_${name}`,
oMyBlob
);
uploadTask.then(async res => {
console.log('file upload finished!');
}).catch(err => {
console.log('file wasnt upload. Error: ' + err);
});
}
}
export { FireBaseService as ExportedClass };