我想显示现在正在使用的代码,以便我可以收到我的问题的解决方案 以下代码用于将图像存储在本地项目文件夹中的API
[HttpPost]
[Route("api/UploadFileApi")]
public HttpResponseMessage Postfiles()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/locker/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
现在在angular2 am当我在UI中的事件绑定属性
时,通过下面的typescript代码调用上面的APIfileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
this.service.fileUpload(formData)
.then(result => {
this.Message = "The Image Uploaded Successfully" + file.name;
});
}
else {
this.Message = "Image Not Uploaded";
}
}
从上面的代码开始,如果我在angular2中使用HttpInterceptor概念,它将进入服务调用(代码下面),localhost附加到URL,在下面的代码之后。
constructor(private http: Http) { }
fileUpload(formData) {
let headers = new Headers();
headers.append("Accept", "multipart/form-data");
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/UploadFileApi', formData, options)
.map((res: Response) => res.json())
.toPromise();
}
但是当调用上面的Post方法时,它会使用backendconnection进入httpinterceptor.post方法,因为我试图在我的项目中使用这个HttpInterceptor概念。下面是代码
post(url: string, formData: any, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url, options);
return super.post(url, formData, this.getRequestOptionArgs(options));
}
//这里是environment.origin4 =“http:// localhost:3636” //返回网址为http://localhost:3636/api/UploadFileApi
private updateUrl(req: string, options?: RequestOptionsArgs) {
return environment.origin4 + req;
}
private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
因此,当调用上述API时,使用httpinterceptor概念时不会传递formData。如果我没有使用httpinterceptor,那么当HttpContext和图像被存储时,图像会通过formData传递给API。
如果我不使用HttpInterceptor概念,我从angular2到API的服务调用就像,所以它工作正常(看看URL的变化)。
fileUpload(formData) {
let headers = new Headers();
headers.append("Accept", "multipart/form-data");
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:3636/api/UploadFileApi', formData, options)
.map((res: Response) => res.json())
.toPromise();
}
但我必须使用HttpInterceptor概念并开发功能,我不知道为什么来自httpinterceptor的帖子没有将formData传递给API。我现在要使用HttpInterceptor.Post调用API