如何使用http POST请求返回文件对象。当我使用POST请求将文件上传到服务器时,一切都按预期工作,因此我知道该文件已保存且未损坏。但是,当我尝试检索文件时,我收到了一个奇怪的回复:console output
最后一个控制台输出是文件上传到服务器时的样子。上面的控制台条目显示了当我尝试从服务器获取文件时返回的响应。文件损坏了吗?
这是我将新文件上传到服务器时的帖子请求:
formData.append('username', localStorage.getItem('username'));
formData.append('subleaseISUcookie', localStorage.getItem('subleaseISUcookie'));
if(fileCount > 0){
formData.append('fileName', inputEl.files[0]);
console.log(inputEl.files[0]);
this.http.post(URL, formData).subscribe(
res => {
//console.log(res);
if(!res['error']){
console.log("no error");
} else {
console.log(res['error']);
}
//this.router.navigate(['login']);
},
err => {
console.log("there was an error");
console.log(err);
}
);
}
这是我从服务器获取文件的方式:
import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ProfilePictureGrabService {
constructor(private http: Http) { }
currUser: string = localStorage.getItem('username');
requestString: string = '/retrieveProfilePicture/' + this.currUser;
getProfilePic(): Observable<any> {
console.log(this.requestString);
// Get the json data string
return this.http.post( this.requestString , {
username: localStorage.getItem('username'),
subleaseISUcookie: localStorage.getItem('subleaseISUcookie')
}).map(res => {
return res;
});
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
最后,这就是我如何调用上述服务来使用http post请求返回的文件对象:
this.profilePictureGrabService.getProfilePic().subscribe( any => {
this.retrievePic = any;
console.log(this.retrievePic);
});
var reader2 = new FileReader();
this.profilePic = this.retrievePic;
if(this.profilePic){
reader2.readAsDataURL(this.profilePic);
}else{
}
reader2.onload = function(){
//localStorage.setItem('profPic', JSON.stringify(inputEl.files[0]));
(<HTMLImageElement>document.getElementById('profilePic')).src = reader2.result;
}
答案 0 :(得分:0)
In your ProfilePictureGrabService class do,
import { Headers, RequestOptions } from '@angular/http';
@Injectable()
export class ProfilePictureGrabService {
headers: any;
options: any
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'text/plain' });
this.options = new RequestOptions({ headers: this.headers });
}
currUser: string = localStorage.getItem('username');
requestString: string = '/retrieveProfilePicture/' + this.currUser;
getProfilePic(): Observable<any> {
console.log(this.requestString);
// Get the json data string
return this.http.post( this.requestString , {
username: localStorage.getItem('username'),
subleaseISUcookie: localStorage.getItem('subleaseISUcookie')
},this.options).map(res => {
return res;
});
}