我在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();
// .....
答案 0 :(得分:0)
首先,从参数中删除MailModels e
,并删除check this tutorial以获取完整的参考信息
Edit1:
您的代码应如下所示:
[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">