![](/img/trans.png)
[英]Getting “415 Unsupported Media Type” when trying to create Hpalm defect using rest api
[英]Trying to POST txt files using web api, getting 415 Unsupported Media Type
進出口新的c#
和目前正在設法POST
幾個txt
文件,使用Web API服務器,無法得到這個工作。 下面這個文章,我append
荷蘭國際集團的文件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() {}); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.