gpt4 book ai didi

javascript - 如何将 Javascript 文件对象+数据发送到 MVC 6 Controller - ASP.NET 5

转载 作者:行者123 更新时间:2023-12-03 07:47:53 25 4
gpt4 key购买 nike

这个 Ajax 位于一个函数内,我知道该函数中有文件和属性。没有发生任何事情,我正在拖放文件,但 Ajax 没有发生任何事情。当我将属性输出到页面时,我看到 JS 中的函数具有该文件,但它不会将其发送到 Controller 。我认为它工作不正常,当我调试索引 Controller 时,我的参数中没有文件属性。 Ajax 没有给我成功或失败警报消息。

我的最终目标是获取上传的文件内的数据,以便我可以解析它。

JavaScript

        function sendFile(file) {


$.ajax({
type: "POST",
url: "HomeController/Index", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { filename: file.name, fileType: file.type, fileSize: file.size },
dataType: "json",
success: function(result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function(result) {
alert('Oh no :(');
}
});

Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);

}

AJAX

            $.ajax({
type: "POST",
url: "HomeController/Index", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { filename: file.name, fileType: file.type, fileSize: file.size },
dataType: "json",
success: function(result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function(result) {
alert('Oh no :(');
}
});

C#

        public IActionResult Index(string fileName, string fileType, int fileSize)
{
ViewBag.Environments = _configHelper.GetEnvironments();
var model = new HomeViewModel { Environment = "DEV" };
return View(model);
}

CSHTML

            <div class="form-group col-md-12">
<label>Company Ids:</label>
<div id="filedrag"><textarea class="form-control" rows="5" id="textAreaCompanyIDs" placeholder="Drop Files Here"></textarea>
</div>
</div>

最佳答案

要在 Controller 中获取文件,您必须发送完整文件。

尝试如下:

AJAX:

 $.ajax({
type: "POST",
url: "HomeController/Index", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { file: file, fileType: file.type, fileSize: file.size },
dataType: "json",
success: function(result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function(result) {
alert('Oh no :(');
}
});

Controller :

   public IActionResult Index(HttpPostedFileBase file, string fileType, int fileSize)
{
ViewBag.Environments = _configHelper.GetEnvironments();
var model = new HomeViewModel { Environment = "DEV" };
return View(model);
}

关于javascript - 如何将 Javascript 文件对象+数据发送到 MVC 6 Controller - ASP.NET 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35132229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com