繁体   English   中英

尝试使用提取API和C#Web API上传图像

[英]Attempting to upload image with fetch api and C# web API

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

{“提供了无效的'HttpContent'实例。它没有以'multipart /'开头的内容类型标头。\\ r \\ n参数名称: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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM