gpt4 book ai didi

c# - 如何将 IFormFile 保存到磁盘?

转载 作者:IT王子 更新时间:2023-10-29 04:02:24 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com