将 Angular 资产中的音频文件发布到服务器
Posting audio files from Angular assets to server
我无法创建如下所示的正确文件对象。它创建了一个大小为 0 的文件对象。
const file = new File([''], '../../assets/' + filename);
const formData: FormData = new FormData();
formData.append('file', file, 'filename.wav');
this.http.post('http://localhost:5000/api',
formData ).subscribe(data => {
console.log('success', data);
}, error => {
console.log(error);
});
我最终首先根据 XhrRequest 的响应创建了一个 Blob,然后将其转换为一个 File 对象。
sender.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class SenderService {
postUrl = 'http://localhost:5000/post_url';
fetchAudioUrl = 'http://localhost:4200/assets/';
constructor(private http: HttpClient) {}
send (audioFile: File) {
const formData: FormData = new FormData();
formData.append('file', audioFile, audioFile.name);
return this.http.post(this.postUrl, formData);
}
getAudio (fileName: string) {
return this.http.get(this.fetchAudioUrl + fileName, { responseType: 'blob'});
}
}
demo.component.ts
import { SenderService } from './sender.service';
@Component({
......
providers: [SenderService]
})
export class DemoComponent {
constructor(private senderService: SenderService) {}
buttonClicked(req: any): void {
this.senderService.getAudio(req.fileName)
.subscribe((data: any) => {
const file = new File([data], req.fileName);
this.senderService.send(file)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
});
});
}
我无法创建如下所示的正确文件对象。它创建了一个大小为 0 的文件对象。
const file = new File([''], '../../assets/' + filename);
const formData: FormData = new FormData();
formData.append('file', file, 'filename.wav');
this.http.post('http://localhost:5000/api',
formData ).subscribe(data => {
console.log('success', data);
}, error => {
console.log(error);
});
我最终首先根据 XhrRequest 的响应创建了一个 Blob,然后将其转换为一个 File 对象。
sender.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class SenderService {
postUrl = 'http://localhost:5000/post_url';
fetchAudioUrl = 'http://localhost:4200/assets/';
constructor(private http: HttpClient) {}
send (audioFile: File) {
const formData: FormData = new FormData();
formData.append('file', audioFile, audioFile.name);
return this.http.post(this.postUrl, formData);
}
getAudio (fileName: string) {
return this.http.get(this.fetchAudioUrl + fileName, { responseType: 'blob'});
}
}
demo.component.ts
import { SenderService } from './sender.service';
@Component({
......
providers: [SenderService]
})
export class DemoComponent {
constructor(private senderService: SenderService) {}
buttonClicked(req: any): void {
this.senderService.getAudio(req.fileName)
.subscribe((data: any) => {
const file = new File([data], req.fileName);
this.senderService.send(file)
.subscribe((data: any) => {
console.log(data);
}, error => {
console.log(error);
});
});
}