c# - 无法从表单 .NET 上传文件
问题描述
我正在尝试将数据(图像)从表单上传到我的 .NET 应用程序。它正确保存了数据库的路径,但图像未保存在“wwwroot/images”下。我会很感激你的帮助。
public async Task<IActionResult> Create([Bind("Id,Brand,Model,Description,Price,ImageUrl,CategoryId")] Car car)
{
if (ModelState.IsValid)
{
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
if (files.Count > 0)
{
string fileName = Guid.NewGuid().ToString();
var uploads = Path.Combine(webRootPath, "images");
var extenstion = Path.GetExtension(files[0].FileName);
var filePath = Path.Combine(uploads, fileName, extenstion);
car.ImageUrl = "images" + "\\" + fileName + extenstion;
using (var filesStreams = new FileStream(filePath, FileMode.Create))
{
files[0].CopyTo(filesStreams);
}
}
_context.Add(car);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name", car.CategoryId);
return View(car);
}
解决方案
推荐阅读
- c# - Net Core 3.1 IHttpClientFactory/HttpClient 第一次请求慢
- php - 更改 url 的命名约定
- vba - 用占位符(标题或正文)替换文本框
- javascript - 嵌套数组的过滤器对象(Javascript)
- javascript - 需要依次调用多个api,在javascript中一个接一个
- r - 如何重新排列R中输入错误的数据?
- c# - WinUI 3.0 - UWP:WebView2 打印功能出错
- java - Jackson 自定义的反序列化运行时异常被 JsonMappingException 包裹
- php - 如何为 -i -t 选项将 Curl 命令转换为 php
- html - 用 DraftJS 中的 span 替换所有根 div 元素?