Asp.net web api 将图像发布到asp.net API 2和angular 2

Asp.net web api 将图像发布到asp.net API 2和angular 2,asp.net-web-api,angular,Asp.net Web Api,Angular,当我尝试将映像发布到ASP.Net API 2时,我得到了415(不支持的媒体类型) 此资源不支持请求实体的媒体类型“multipart/form data”。,“exceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型为“multipart/form data”的内容中读取“Attachment”类型的对象 我的后端发布方法: [HttpPost] [Route("api/listing/{listingId}/Attachment/")]

当我尝试将映像发布到ASP.Net API 2时,我得到了415(不支持的媒体类型) 此资源不支持请求实体的媒体类型“multipart/form data”。,“exceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型为“multipart/form data”的内容中读取“Attachment”类型的对象

我的后端发布方法:

    [HttpPost]
    [Route("api/listing/{listingId}/Attachment/")]
    public async Task<dynamic> Post([FromBody] Attachment model)
    {

        var Attachments = new Attachment
        {

            ListingId = model.ListingId,
            Content = model.Content,
            Description = model.Description,
            Name = model.Name,
            MimeType = model.MimeType,
            Size = model.Size,
            CreatedOn = DateTime.UtcNow,
            UpdatedOn = model.UpdatedOn,
        };

        return await DataStore.InsertDynamicAsync(Attachments);
    } 
[HttpPost]
[路由(“api/listing/{listingId}/Attachment/”)
公共异步任务发布([FromBody]附件模型)
{
var附件=新附件
{
ListingId=model.ListingId,
Content=model.Content,
Description=型号.Description,
Name=model.Name,
MimeType=model.MimeType,
尺寸=型号。尺寸,
CreatedOn=DateTime.UtcNow,
UpdatedOn=model.UpdatedOn,
};
return wait DataStore.InsertDynamicAsync(附件);
} 
我的前端方法:

  onChangeImage(e: any) {
      console.log(this.className + 'onChangeImage.event=' +JSON.stringify(event));
console.log(this.className + 'onChangeImage._listingAttachmentService undefined?: ' + (this._listingAttachmentService === undefined));
const inputElement = this.fileInput.nativeElement;

const fileList = inputElement.files;
const files = [];
console.log('AttachmentsTabComponent: file count = ' + fileList.length);

if (fileList.length > 0) {

  for (let i = 0; i < fileList.length; i++) {

    // get item
    const file = fileList.item(i);
    files.push(file);
    const model: Attachment = {
      listingId: this.listing.id,

      mimeType: file.type,
      name: file.name,
      size: file.size,
      updatedOn: file.lastModifiedDate
    };



    const reader = new FileReader();
    reader.readAsDataURL(file);

    console.log(this.className + 'onChangeImage.listingAttachmentService (before reader.onload) undefined?: ' + (this._listingAttachmentService === undefined));

    reader.onload = (readerEvt: any) => {
      const binaryString = readerEvt.target.result;

      //base-64 encoded ASCII string
      model.content = btoa(binaryString);

      console.log(this.className + 'onChangeImage.listingAttachmentService (during reader.onload) undefined?: ' + (this._listingAttachmentService === undefined));

      console.log(this.className + 'ListingAttachmentModel.content.length=' + JSON.stringify(model.content.length));
      // this._listingAttachmentService.add(model);
    };
  }

  // try to clear the file input
  try {
    // TODO: fix this
    this.fileForm.nativeElement.reset();
    inputElement.value = '';
    if (inputElement.value) {
      inputElement.type = 'text';
      inputElement.type = 'file';
    }
  } catch (e) { }

  this._listingAttachmentService.upload(this.listing.id, files)
    .subscribe(data => {
      this.listing.attachments = data;
    });
}
    }
onChangeImage(e:any){
log(this.className+'onChangeImage.event='+JSON.stringify(event));
log(this.className+'onChangeImage.\u listingAttachmentService未定义?:'+(this.\u listingAttachmentService==未定义));
const inputElement=this.fileInput.nativeElement;
const fileList=inputElement.files;
常量文件=[];
log('AttachmentsTabComponent:file count='+fileList.length);
如果(fileList.length>0){
for(设i=0;i{
const binaryString=readerEvt.target.result;
//base-64编码的ASCII字符串
model.content=btoa(二进制字符串);
console.log(this.className++'onChangeImage.listingAttachmentService(在reader.onload期间)未定义?:'+(this.u listingAttachmentService==未定义));
log(this.className+'ListingAttachmentModel.content.length='+JSON.stringify(model.content.length));
//此._listingAttachmentService.add(模型);
};
}
//尝试清除文件输入
试一试{
//TODO:解决这个问题
this.fileForm.nativeElement.reset();
inputElement.value='';
if(inputElement.value){
inputElement.type='text';
inputElement.type='文件';
}
}捕获(e){}
此.u listingAttachmentService.upload(this.listing.id,文件)
.订阅(数据=>{
this.listing.attachments=数据;
});
}
}
还有我的listingAttachmentService

upload(listingId: number, files: Array<File>) {

this._logger.debug('method upload() entered');
this._logger.debug('upload() listingId=' + listingId);
this._logger.debug('this.fileToUpload.length=' + files.length);

var self = this;

return Observable.create(observer => {
  console.log('creating Observable');
  let formData: FormData = new FormData(),
    xhr: XMLHttpRequest = new XMLHttpRequest();

  formData.append('listingId', listingId);
  for (let i = 0; i < files.length; i++) {
    formData.append('uploads[]', files[i], files[i].name);
  }

  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        observer.next(JSON.parse(xhr.response));
        observer.complete();
      } else {
        observer.error(xhr.response);
      }
    }
  };

  let newbaseUrl = self.baseUrl + listingId + '/attachment/' ;
  xhr.open('POST', newbaseUrl, true);
  xhr.send(formData);
})
  .catch(this.handleError);
}
上传(listingId:number,files:Array){
这是.u logger.debug('method upload()entered');
这是.u logger.debug('upload()listingId='+listingId);
this._logger.debug('this.fileToUpload.length='+files.length);
var self=这个;
返回可观察的。创建(观察者=>{
console.log(“创建可观察的”);
让formData:formData=new formData(),
xhr:XMLHttpRequest=新的XMLHttpRequest();
formData.append('listingId',listingId);
for(设i=0;i{
if(xhr.readyState==4){
如果(xhr.status==200){
next(JSON.parse(xhr.response));
observer.complete();
}否则{
观察者错误(xhr响应);
}
}
};
让newbaseUrl=self.baseUrl+listingId+'/attachment/';
xhr.open('POST',newbaseUrl,true);
xhr.send(formData);
})
.接住(这个.把手错误);
}

您应该使用自定义的MediaTypeFormatter。这里有更多信息:这里有一个示例

下面是一个帖子

POST http://localhost/api/FileUpload HTTP/1.1
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Content-Length: 88778

---------------------------acebdf13572468
Content-Type: application/json; charset=utf-8
Content-Disposition: form-data; name=attachment

{"ListingId":"testl"}
---------------------------acebdf13572468
Content-Disposition: form-data; name=image; filename=image.jpg
Content-Type: image/jpeg

Image content
---------------------------acebdf13572468--

希望这能有所帮助。

您能检查我的答案吗?我检查了您的答案,但收到500个内部服务器错误,错误消息为“发生了错误”。,“exceptionMessage”:“对象引用未设置为对象的实例”stackTrace:“at OutdoorAccess.Api.Utilities.CustomFormatter.c.b_u3_0(HttpContent c)在C:\\Users\\keroles.hakem\\Documents\\mvp\\web api\\OutdoorAccess.api\\Utilities\\CustomFormatter.cs中:System.Linq.Enumerable.FirstOrDefault[TSource]的第36行\r\n(IEnumerable
1 source,Func
2谓词)在OutdoorAccess.api.Utilities.CustomFormatter.d\u 3.MoveNext()在C:\\Users\\keroles.hakem\\Documents\\mvp\\web api\\OutdoorAccess.api\\Utilities\\CustomFormatter.cs:line 35\r\n---End of stack trace from…}中,您的文章似乎没有内容类型:image/jpeg。您正在上载的图像的内容类型是什么?您可以对文章进行fiddler跟踪并在此处更新吗?我正在使用Observab请看一下onChangeImage()方法并在我的问题中上载。能否在
xhr.setRequestHeader(“内容类型”,“图像/jpeg”);
之前添加
xhr.send(formData);
private void ConfigureWebApi(HttpConfiguration config)
{
    //other code here
    config.Formatters.Add(new CustomFormatter());
}   
POST http://localhost/api/FileUpload HTTP/1.1
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Content-Length: 88778

---------------------------acebdf13572468
Content-Type: application/json; charset=utf-8
Content-Disposition: form-data; name=attachment

{"ListingId":"testl"}
---------------------------acebdf13572468
Content-Disposition: form-data; name=image; filename=image.jpg
Content-Type: image/jpeg

Image content
---------------------------acebdf13572468--