简体   繁体   中英

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

I have inherited the following C# code to upload an image, and I am attempting to try to call the endpoint using the fetch api. Error I keep receiving:

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

Any idea what I am doing wrong with calling this endpoint? I have included the C#/web api code, and the javascript code beneath that. Thanks for any help you can provide.

[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 code:

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

I think you should try as follows...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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