作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试使用 this piece of code 将文件保存在磁盘上.
IHostingEnvironment _hostingEnvironment;
public ProfileController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files)
{
foreach (var file in files)
{
var fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var filePath = _hostingEnvironment.WebRootPath + "\\wwwroot\\" + fileName;
await file.SaveAsAsync(filePath);
}
return View();
}
我能够用 IHostingEnvironment 替换 IApplicationEnvironment,用 WebRootPath 替换 ApplicationBasePath。
IFormFile 似乎不再有 SaveAsAsync()。那么如何将文件保存到磁盘呢?
最佳答案
自 core 发布候选版本以来,一些事情发生了变化
public class ProfileController : Controller {
private IWebHostEnvironment _hostingEnvironment;
public ProfileController(IWebHostEnvironment environment) {
_hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files) {
string uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
foreach (IFormFile file in files) {
if (file.Length > 0) {
string filePath = Path.Combine(uploads, file.FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create)) {
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
}
关于c# - 如何将 IFormFile 保存到磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39322085/
我是一名优秀的程序员,十分优秀!