我是Asp.net核心的新手,我想上传图片。我一直在关注此视频(https://www.youtube.com/watch?v=Fx-EQ1hT8R0)。在运行应用程序时,当我选择图像并单击提交时,该程序会自动关闭。我不知道错误出在哪里。
这是HTML页面:
<form method="post" enctype="multipart/form-data">
<p>
<input type="file" name="uploadfiles" />
<input type="submit" value="Upload" class="btn btn-primary" />
</p>
</form>
这是IndexModel页面:
public class IndexModel : PageModel
{
private readonly Razorpages_FileUploadContext _context;
private readonly IWebHostEnvironment _environment;
public IndexModel(Razorpages_FileUploadContext context, IWebHostEnvironment environment)
{
_context = context;
_environment = environment;
}
public IList<ImageSave> ImageSave { get; set; }
public async Task OnGetAsync()
{
ImageSave = await _context.ImageSave.ToListAsync();
}
public async Task<IActionResult> OnPostAsync(IFormFile uploadfiles, ImageSave img)
{
if (!ModelState.IsValid)
{
return Page();
}
string imgext = Path.GetExtension(uploadfiles.FileName);
if (imgext == ".jpg" || imgext == ".png" || imgext == ".gif")
{
var imgsave = Path.Combine(_environment.WebRootPath, "Images", uploadfiles.FileName);
var stream = new FileStream(imgsave, FileMode.Create);
await uploadfiles.CopyToAsync(stream);
stream.Close();
img.Imgname = uploadfiles.FileName;
img.Imgpath = imgsave;
await _context.ImageSave.AddAsync(img);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
}
我上传图像并提交,程序关闭,cmd中的错误消息:D:\ c_sharp \ LearnRazorPages \ Razorpages_FileUpload \ Razorpages_FileUpload \ bin \ Debug \ netcoreapp3.1 \ Razorpages_FileUpload.exe(进程12992)已退出,代码为-1 。要在调试停止时自动关闭控制台,请启用工具->选项->调试->在调试停止时自动关闭控制台。
请你帮我!