尝试使用web api发布txt文件,获得415不支持的媒体类型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试使用web api发布txt文件,获得415不支持的媒体类型相关的知识,希望对你有一定的参考价值。
我是c#
的新手,目前正在尝试使用web API将POST
几个txt
文件发送到服务器,无法让这个工作。在this文章之后,我将append
ing文件发送到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
答案
根据您的回复,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() {});
}
以上是关于尝试使用web api发布txt文件,获得415不支持的媒体类型的主要内容,如果未能解决你的问题,请参考以下文章
Web API Post 返回 415 - 不支持的媒体类型
调用 Web API 2 端点时出现 HTTP 415 不支持的媒体类型错误
将整数列表发送到 REST API 会引发 415(不支持的媒体类型)