我试图在asp.net core 2 razor页面上进行简单的文件上传。我有下面的代码。请意识到它是不完整的。当我在我的VS2017中运行时,我检查了我的FileUpload对象,遗憾的是它是null。我希望它是除null之外的东西,我可以创建一个流来从中获取一些数据。但是,如果对象为null,我会怀疑我没有正确绑定的东西。任何想法都表示赞赏。感谢。
cs背后的代码:
public class PicturesModel : PageModel
{
public PicturesModel()
{
}
[Required]
[Display(Name = "Picture")]
[BindProperty]
public IFormFile FileUpload { get; set; }
public async Task OnGetAsync()
{
}
public async Task<IActionResult> OnPostAsync()
{
//FileUpload is null
return RedirectToPage("/Account/Pictures");
}
}
前端cshtml文件;
<form method="post" enctype="multipart/form-data">
<label asp-for="FileUpload"></label>
<input type="file" asp-for="FileUpload" id="file" name="file" />
<input type="submit" value="Upload" />
</form>
答案 0 :(得分:2)
您输入文件的属性名为FileUpload
,但您已覆盖TagHelper生成的name
属性,并将其重命名为file
,该属性与属性名称不匹配。
将视图代码更改为
<input type="file" asp-for="FileUpload" />
以便它生成正确的name
属性(name="FileUpload"
)。另请注意删除id="file"
,这意味着您<label>
在单击时不会将焦点设置到关联的控件上。
答案 1 :(得分:0)
Post方法中没有文件参数。
在这里查看教程: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
答案 2 :(得分:0)
我今天早上花了很多时间尝试各种解决方案,但似乎都没有。但最终,我想出了这个......享受。
/// <summary>
/// Upload a .pdf file for a particular [User] record
/// </summary>
[AllowAnonymous]
[HttpPost("uploadPDF/{UserId}")]
public async Task<IActionResult> uploadPDF(string UserId, IFormFile inputFile)
{
try
{
if (string.IsNullOrEmpty(UserId))
throw new Exception("uploadPDF service was called with a blank ID.");
Guid id;
if (!Guid.TryParse(RequestId, out id))
throw new Exception("uploadPDF service was called with a non-GUID ID.");
var UserRecord = dbContext.Users.FirstOrDefault(s => s.UserID == id);
if (UserRecord == null)
throw new Exception("User record not found.");
var UploadedFileSize = Request.ContentLength;
if (UploadedFileSize == 0)
throw new Exception("No binary data received.");
var values = Request.ReadFormAsync();
IFormFileCollection files = values.Result.Files;
if (files.Count == 0)
throw new Exception("No files were read in.");
IFormFile file = files.First();
using (Stream stream = file.OpenReadStream())
{
BinaryReader reader = new BinaryReader(stream);
byte[] bytes = reader.ReadBytes((int)UploadedFileSize);
Trace.WriteLine("Saving PDF file data to database..");
UserRecord.RawData = bytes;
UserRecord.UpdatedOn = DateTime.UtcNow;
dbContextWebMgt.SaveChanges();
}
return new OkResult();
}
catch (Exception ex)
{
logger.LogError(ex, "uploadPDF failed");
return new BadRequestResult();
}
}