【问题标题】:Attempting to upload image with fetch api and C# web API尝试使用 fetch api 和 C# web API 上传图像
【发布时间】:2017-12-29 01:01:16
【问题描述】:

我继承了以下 C# 代码来上传图像,我正在尝试使用 fetch api 调用端点。 我不断收到错误:

{"提供的 'HttpContent' 实例无效。它没有以 'multipart/' 开头的内容类型标头。\r\n参数名称:内容"}

知道我在调用这个端点时做错了什么吗?我已经包含了 C#/web api 代码,以及下面的 javascript 代码。感谢您的任何帮助,您可以提供。

[Route( "coverpicture" )]
public virtual Task<HttpResponseMessage> Post()
{
    HttpContext.Current.Response.ContentType = "application/json";
    var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    var personId = CurrentUser.PersonId;

    if ( !Request.Content.IsMimeMultipartContent() )
    {
        throw new HttpResponseException( HttpStatusCode.UnsupportedMediaType );
    }

    var task = Request.Content.ReadAsMultipartAsync().ContinueWith( t =>
        {
            var parts = t.Result.Contents;
            var content = parts.First( x => x.Headers.ContentDisposition.Name.Contains( "CoverPicture" ) );

            if ( content == null )
            {
                var resp = new HttpResponseMessage( HttpStatusCode.NotAcceptable )
                {
                    Content = new ObjectContent<string>( "No ContentDisposition named CoverPicture.", formatter )
                };
                return resp;
            }

            using ( var imgStream = content.ReadAsStreamAsync().Result )
            using ( var photos = new PhotosProvider() )
            {
                var photo = photos.CreateOrUpdateCoverPicture( personId, imgStream );
                var resp = new HttpResponseMessage( HttpStatusCode.OK )
                    {
                        Content = new ObjectContent<Photo>( photo, formatter )
                    };
                return resp;
            }
        } );

    return task;
}

Javascript 代码:

let data = new FormData()
for (var x = 0; x < files.length; x++){
    data.append("file" + x, files[x]);
}
fetch(url, {
    method: 'POST',
    mode: 'cors',
    contentType: false,
    processData: false,
    body: JSON.stringify({}),
    data: data
})
.then(parseResponse)
.then(resolve)
.catch(reject);

【问题讨论】:

    标签: javascript c#


    【解决方案1】:

    我认为你应该尝试如下...

    let data = new FormData()
    for (var x = 0; x < files.length; x++){
        data.append("file" + x, files[x]);
    }
    fetch(url, {
        method: 'POST',
        mode: 'cors',
        body:  data
    })
    .then(parseResponse)
    .then(resolve)
    .catch(reject);
    

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2016-06-24
      • 2018-04-27
      • 2021-03-25
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多