javascript - 尝试使用 fetch api 和 C# Web API 上传图像

标签 javascript c#

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

{"Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.\r\nParameter name: content"}

知道我调用此端点时做错了什么吗?我已经包含了 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);

最佳答案

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

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);

关于javascript - 尝试使用 fetch api 和 C# Web API 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48016213/

相关文章:

c# - Xamarin iOS 错误 : Can not resolve reference

c# - Monogame, Nez : Switching scenes, 打开菜单

javascript - 网站滚动问题

javascript - HTML5 模式下的 Angular-ui 嵌套 View 获取 404 未找到模板文件

c# - 与 C# 中的泛型类型有些混淆

c# - 如何在 .NET Core 2.1 中使用 System.Security.Principal.WindowsIdentity

c# - wpf Canvas 双击

javascript - 从数组中选择特定数字

javascript - Node JS 异步/等待 Controller 问题

javascript - 如何改变滚动时的背景颜色?