[英]Uploading file - ASP.NET Core MVC
我的 ASP.NET Core 項目中有一個聯系表單,它可以工作。 但是現在,我想上傳一個文件。 這是我的代碼:
模型:
namespace WebApplication1.Models
{
public class MailModels
{
[StringLength(5)]
public string Name { get; set; }
[StringLength(5)]
public string SurName { get; set; }
//[StringLength(5, ErrorMessage = "First name cannot be longer than 50 characters.")]
public string Email { get; set; }
public string Telephone { get; set; }
[StringLength(1000)]
public string Message { get; set; }
public IFormFile FileUploading { get; set; }
}
}
視圖(部分視圖):
<label class="file_uploading">
@Html.TextBoxFor(m => m.FileUploading, new { type = "file", @class = "input-file" })
</label>
控制器(控制器的一部分):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index2(MailModels e, IFormFile file)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("Name: " + e.Name + "\n");
message.Append("Surname: " + e.SurName + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n\n");
message.Append("Text: " + e.Message + "\n");
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
// .....
首先,從參數中刪除MailModels e
,並查看本教程以獲取完整參考
編輯1:
您的代碼應如下所示:
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
你的表格應該是這樣的:
<form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.