(.Net Core) 完整的工作示例。该答案的某些部分采用了上面的答案,并修复了编译错误。
假设您想要上传文件,然后将使用已上传的文件提交表单。
Register.cshtml
@using UploadFileAjaxPostWebApp.Models.Account
@model RegisterModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
<div>
<label>First Name </label>
<input type="text" name="FirstName" value="John" />
</div>
<div>
<label>Second Name </label>
<input type="text" name="SecondName" value="Smith" />
</div>
<div>
<label>Resume</label>
<input type="file" id="fileUpload1" onchange="uploadFiles('fileUpload1');" />
<input type="hidden" id="ResumeFileName" name="ResumeFileName" value="@Model.ResumeFileName" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
<script type="text/javascript">
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i !== files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "/account/uploadfiles",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
// Set the property of the Model.
$("
alert("Files Uploaded! " + data.fileName);
}
}
);
}
</script>
<账户控制器:>
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using UploadFileAjaxPostWebApp.Models.Account;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace UploadFileAjaxPostWebApp.Controllers
{
public class AccountController : Controller
{
private readonly IWebHostEnvironment _hostEnvironment;
public AccountController(IWebHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
public IActionResult Register()
{
RegisterModel model = new RegisterModel();
return View(model);
}
[HttpPost]
public IActionResult Register(RegisterModel model)
{
return View(model);
}
[HttpPost]
public async Task<ActionResult> UploadFiles(IList<IFormFile> files)
{
string fileName = null;
foreach (IFormFile source in files)
{
string orgFileName = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Value;
fileName = DateTime.Now.ToFileTime() + Path.GetExtension(orgFileName);
string fullPath = GetFullPathOfFile(fileName);
Directory.CreateDirectory(Directory.GetParent(fullPath).FullName);
await using FileStream output = System.IO.File.Create(fullPath);
await source.CopyToAsync(output);
}
var response = new { FileName = fileName };
return Ok(response);
}
private string GetFullPathOfFile(string fileName)
{
return $"{_hostEnvironment.WebRootPath}\\uploads\\{fileName}";
}
}
}
RegisterModel类
namespace UploadFileAjaxPostWebApp.Models.Account
{
public class RegisterModel
{
public string FirstName { get; set; }
public string SecondName { get; set; }
public string ResumeFileName { get; set; }
}
}
data: {formData:formData}
?在public async Task<JsonResult> UploadFile(IFormFile formData)
中,formData
期望是什么?Task<JsonResult>
的目的是什么? - guest271314