Ошибка ajax post запроса к серверу "net::ERR_CONNECTION_RESET"
На странице "Index.cshtml" проекта Web-application C# есть функция ajax, которая по нажатию на кнопку должна загружать файл на сервер:
<script type="text/javascript">
import { error } from "jquery";
$("#btnUpload").click(function () {
var data = new FormData();
var files = $("#uploadFile").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
data.append("wayFile", $("#wayFile").val()); //Other data
var ajaxRequest = $.ajax({
type: "POST",
url: "http://localhost:44367/api/FileApi/UploadFile",
contentType: false,
processData: false,
data: data,
success: function (response) {
alert('File uploaded');
console.log(response);
},
error: function (result, status, er) {
alert("error: " + result + " status: " + status + " er:" + er);
}
});
return false;
});
</script>
На неё отвечает следующий контроллер:
public class FileApiController : ApiController
{
[HttpPost]
[Route("api/FileApi/UploadFile")]
public void UploadFile()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
try
{
foreach (var fileName in HttpContext.Current.Request.Files.AllKeys)
{
HttpPostedFile file = HttpContext.Current.Request.Files[fileName];
if (file != null)
{
FileDTO fileDTO = new FileDTO();
fileDTO.FileActualName = file.FileName;
fileDTO.FileExt = Path.GetExtension(file.FileName);
fileDTO.ContentType = file.ContentType;
//Generate a unique name using Guid
fileDTO.FileUniqueName = Guid.NewGuid().ToString();
//Get physical path of our folder where we want to save images
var rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
var fileSavePath = System.IO.Path.Combine(rootPath, fileDTO.FileUniqueName + fileDTO.FileExt);
file.SaveAs(fileSavePath);
//Save File Meta data in Database
FileModel.SaveFileInDB(fileDTO);
}
}//end of foreach
}
catch (Exception ex)
{ }
}
var age = HttpContext.Current.Request["wayFile"];
}
}
Но выдает следующею ошибку:
POST http://localhost:44367/api/FileApi/UploadFile net::ERR_CONNECTION_RESET send @ jquery-3.4.1.js:9837 ajax @ jquery-3.4.1.js:9434 (anonymous) @ Index:82 dispatch @ jquery-3.4.1.js:5237 elemData.handle @ jquery-3.4.1.js:5044
Добавил в контроллер С# обрабатывающий данный запрос код HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*"); - ошибка пропала, но действий (загрузки) не происходит
[HttpPost]
[Route("api/FileApi/UploadFile")]
public void UploadFile()
{
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.Files.Count > 0)
{
try
{
foreach (var fileName in HttpContext.Current.Request.Files.AllKeys)
{
HttpPostedFile file = HttpContext.Current.Request.Files[fileName];
if (file != null)
{
FileDTO fileDTO = new FileDTO();
fileDTO.FileActualName = file.FileName;
fileDTO.FileExt = Path.GetExtension(file.FileName);
fileDTO.ContentType = file.ContentType;
//Generate a unique name using Guid
fileDTO.FileUniqueName = Guid.NewGuid().ToString();
//Get physical path of our folder where we want to save images
var rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
var fileSavePath = System.IO.Path.Combine(rootPath, fileDTO.FileUniqueName + fileDTO.FileExt);
// Save the uploaded file to "UploadedFiles" folder
file.SaveAs(fileSavePath);
//Save File Meta data in Database
FileModel.SaveFileInDB(fileDTO);
}
}//end of foreach
}
catch (Exception ex)
{ }
}//end of if count > 0
var age = HttpContext.Current.Request["wayFile"];
}
Перeписал ajax немного по другому - как просто отдельную функцию, а в button прописал акшен onclic, повесил на него эту функцию. Не знаю почему, но так заработало
<input type="button" id="btnUpload" value="Upload" onclick="RequestUpload()"/>
function RequestUpload(){
var data = new FormData();
var files = $("#uploadFile").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
data.append("infoFile", $("#infoFile").val()); //Other data
$.ajax({
type: "POST",
url: "http://localhost:6141/api/FileApi/UploadFile",
contentType: false,
processData: false,
data: data,
success: function (response) {
alert('File uploaded');
console.log(response);
},
error: function (result, status, er) {
alert("error: " + result + " status: " + status + " er:" + er);
}
});
}