尝试使用web api发布txt文件,获得415不支持的媒体类型

问题描述 投票:0回答:1

我是c#的新手,目前正在尝试使用web API将POST几个txt文件发送到服务器,无法让这个工作。在this文章之后,我将appending文件发送到formData并使用以下代码发布它:

public uploadMethod(formDataWithFiles) {
    return this.$http.post("/actionApi/Utils/UploadFile", formDataWithFiles).then((res) => {
        return res;
    }).catch((err) => {
        return err;
    });
}

这是应该接收文件并解析它们的后端代码:

public async Task<HttpResponseMessage> UploadFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The request doesn't contain valid content!");
    }

    try
    {
        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var dataStream = await file.ReadAsStreamAsync();
            // use the data stream to persist the data to the server (file system etc)

            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain");
            response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"text/html");
            return response;
        }
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,"problem.");

    }
    catch (Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
    }
}

我得到的例外:

无法加载资源:服务器响应状态为415(不支持的媒体类型)

请求机构:

General:

    Request URL: http://localhost:48738/actionApi/Utils/UploadFile
    Referrer Policy: no-referrer-when-downgrade

Request Headers:
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer _en....
Origin: http://localhost:48738
Referer: http://localhost:48738/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 

(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36

Request Patload:
------WebKitFormBoundaryYAuasRL66eAdhUtd
Content-Disposition: form-data; name="34.txt"; filename="34.txt"
Content-Type: text/plain


------WebKitFormBoundaryYAuasRL66eAdhUtd
Content-Disposition: form-data; name="35.txt"; filename="35.txt"
Content-Type: text/plain
javascript c# post asp.net-web-api
1个回答
2
投票

根据您的回复,http标头Content-Type不正确,应该是Content-Type: multipart/form-data

这可能是由您的Javascript代码引起的,因此请使用下面的代码作为如何为angularJS触发文件上传ajax的示例

var filedata = $("#fileupload").prop("files")[0];
var formData = new FormData();
formData.append("file", filedata);
var uploadUrl = "/actionApi/Utils/UploadFile";
uploadMethod(uploadUrl, formData);

function uploadMethod(uploadUrl, form_data) {
  $http
    .post(uploadUrl, form_data, {
      transformRequest: angular.identity,
      headers: { "Content-Type": undefined }
    })
    .success(function() {})
    .error(function() {});
}
© www.soinside.com 2019 - 2024. All rights reserved.