在ASP.Net Core MVC中使用AJAX提交表单 [英] Submit a Form using AJAX in ASP.Net Core MVC
问题描述
我正在使用ASP.Net Core 2.1,并尝试在返回文件的URL的同时上传文件,而不刷新页面.
I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
我正在尝试在site.js中编写JavaScript,因为_RenderPartial("scripts")会在页面末尾呈现所有脚本,因此在razor视图中直接使用script标签无效.其次,将其添加到site.js中使我有机会在整个网站视图中调用该脚本.
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
我的控制器动作如下:
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
我的视图如下:
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
site.js当前看起来像:
The site.js currently looks like :
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
当前,该代码绕过了整个脚本,并上传了文件,并返回了显示文件名的新视图.我需要帮助来创建javascript.
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
推荐答案
不幸的是,jQuery serialize()
方法将不包含输入文件元素.因此,用户选择的文件不会包含在序列化值(基本上是字符串)中.
Unfortunately the jQuery serialize()
method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).
您可能要做的是,创建一个 FormData
对象,然后将文件附加到该对象.制作时ajax调用,您需要将 processData
和 contentType
属性值指定为 false
What you may do is, create a FormData
object, append the file(s) to that. When making the
ajax call, you need to specify processData
and contentType
property values to false
<form id="FileUploadForm" asp-action="Upload" asp-controller="Home"
method="post" enctype="multipart/form-data">
<input id="uploadfile" type="file" />
<button name="uploadbtn" type="submit">Upload</button>
</form>
在这里以统一的方式处理表单提交事件,我们将停止常规行为并改为执行ajax提交.
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
$(function () {
$("#FileUploadForm").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
var formAction = $(this).attr("action");
var fdata = new FormData();
var fileInput = $('#uploadfile')[0];
var file = fileInput.files[0];
fdata.append("file", file);
$.ajax({
type: 'post',
url: formAction,
data: fdata,
processData: false,
contentType: false
}).done(function (result) {
// do something with the result now
console.log(result);
if (result.status === "success") {
alert(result.url);
} else {
alert(result.message);
}
});
});
})
假设您的服务器端方法的参数名称与创建 FormData
对象条目( file
)时使用的名称相同.这是一个示例,它将图像上传到 wwwwroot
内的 uploads
目录.
Assuming your server side method has a parameter of with name same as the one we used when we created the FormData
object entry(file
). Here is a sample where it will upload the image to the uploads
directory inside wwwwroot
.
action方法返回一个带有状态和url/message属性的JSON对象,您可以在ajax调用的成功
/完成
处理程序中使用该对象想做.
The action method returns a JSON object with a status and url/message property and you can use that in the success
/done
handler of the ajax call to whatever you want to do.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
_context = context;
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
var url = Url.Content("~/uploads/" + uniqueFileName);
return Json(new { status = "success", url = url });
}
catch(Exception ex)
{
// to do : log error
return Json(new { status = "error", message = ex.Message });
}
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
这篇关于在ASP.Net Core MVC中使用AJAX提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!