我正在使用ASP.Net Core 2.0和Razor Pages处理应用程序。我一直在关注如何将文件上传到Azure blob存储的Microsoft Docs,但到目前为止我还无法使用它。
我有两个独立的模型类。一个用于文件上载,一个用于Word。
文件上传类:
error: use of deleted function ‘const _Tp* std::addressof(const _Tp&&) [with _Tp = model*]’
其他课程:
public class WordUpload
{
public IFormFile SoundFile { get; set; }
public IFormFile SoundFileSentence { get; set; }
}
使用未传递的WordUpload.SoundFile的页面。这是问题,因为它总是返回null。
public class Word
{
public int ID { get; set; }
public string Answer { get; set; }
public string AlternativeAnswer { get; set; }
public string Hint { get; set; }
public int Length { get; set; }
public int Vowels { get; set; }
public string Language { get; set; }
public string Category { get; set; }
public int Module { get; set; }
public string Difficulty { get; set; }
public string Sound { get; set; }
public string SoundSentence { get; set; }
}
视图 - 页面:
public class CreateModel : PageModel
{
private readonly Data.ApplicationDbContext _context;
private readonly IWordRepository _wordRepository;
public CreateModel(Data.ApplicationDbContext context, IWordRepository wordRepository)
{
_context = context;
_wordRepository = wordRepository;
}
/// <summary>
/// OnGet triggers when the page is opened
/// </summary>
/// <returns></returns>
public IActionResult OnGet()
{
Word = new Word
{
Answer = "",
AlternativeAnswer = "",
Hint = "Hint",
Length = 0,
Vowels = 0,
Language = "DK",
Category = "",
Module = 0,
Difficulty = "",
Sound = "",
SoundSentence = ""
};
return Page();
}
[BindProperty]
public WordUpload WordUpload { get; set; }
[BindProperty]
public Word Word { get; set; }
/// <summary>
/// Posts the data to the database async
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
// Get the number of vowels in the word
Word.Vowels = _wordRepository.NumberOfVowels(Word.Answer);
// Save the length
Word.Length = Word.Answer.Length;
// upload file to blob storage
Word.Sound = _wordRepository.UploadAudio(WordUpload.SoundFile);
// save to db
_context.Word.Add(Word);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
WordUpload.SoundFile不随模型传递。当我调试应用程序时,它在控制器/页面中返回为null。所有其他属性都没有任何问题。
你知道如何传递文件吗?
答案 0 :(得分:3)
您需要在表单上添加:
<form method="post" enctype="multipart/form-data">
在你的post方法中,如果模型绑定没有将文件绑定到模型有任何问题,你可以直接从Form.Files中获取它,如下所示:
var formFile = HttpContext.Request.Form.Files[0];
你应该先检查HttpContext.Request.Form.Files.Length&gt; 0或该代码将引发错误。然后将字节复制到模型以进行保存。 另请参阅documentation