我想在 Angular 应用程序中将文件发送到 Infura 的 IPFS API。我知道 ipfs-http-client 已被弃用,所以我尝试使用 POST 调用 API。
应用程序组件:
onFileSelected(event: Event){
var inputElement = event.target as HTMLInputElement;
if (inputElement?.files && inputElement.files.length > 0) {
this.fcUploadFile = inputElement.files[0];
var reader = new FileReader();
reader.onload = (e) => {
var fileContent = e.target?.result;
this.IpfsService.uploadToIpfs(fileContent);
console.log("File content: ", fileContent);
};
reader.readAsArrayBuffer(this.fcUploadFile);
console.log('File selected:', this.fcUploadFile);
} else {
console.error('No file selected.');
}
}
(我的控制台输出为空)
IPFS服务:
export class IpfsService {
private readonly apiUrl: 'https://ipfs.infura.io:5001/api/v0/add?pin=true';
constructor(private http: HttpClient){}
uploadToIpfs(file: any){
const formData = new FormData();
formData.append('file', file); //formData
const headers = new HttpHeaders({
Authorization: 'Basic '+ btoa('API KEY:API SECRET')
});
var res = this.http.post(this.apiUrl, formData, { headers });
console.log(res); //=> Empty observable displayed
return res;
}
}
我尝试在不使用“ipfs-http-client”的情况下发出发布请求。我本来期望收到上传文件的cid,但结果是空的
ipfs-http-client 仍然有效:
const projectId = 'ID';
const projectSecret = 'SECRET';
const auth = 'Basic ' + btoa(projectId + ':' + projectSecret);
const cl = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
cl.add(f).then((res: any) => {
console.log("IPFS Response: " , res.path);
return res.path;
});