Ada*_*abo 6 asp.net-core-mvc asp.net-core
在MVC 5中我曾经这样做过:
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
var file = (HttpPostedFileBase)context.Request.Files[0];
Run Code Online (Sandbox Code Playgroud)
现在这些在vCxt下的MVC 6中不可用.如何从请求中获取文件?
以下答案是关于beta6版本.
它现在在框架中.到目前为止,有一些警告,要获取上传的文件名,您必须解析标题.你必须在你的控制器中注入IHostingEnvironment才能到达wwwroot文件夹位置,因为没有更多的Server.MapPath()
以此为例:
public class SomeController : Controller
{
private readonly IHostingEnvironment _environment;
public SomeController(IHostingEnvironment environment)
{
_environment = environment;
}
[HttpPost]
public ActionResult UploadFile(IFormFile file)//, int Id, string Title)
{
if (file.Length > 0)
{
var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("Content\\Uploaded\\"));
var fileName = GetFileName(file);
var savePath = Path.Combine(targetDirectory, fileName);
file.SaveAs(savePath);
return Json(new { Status = "Ok" });
}
return Json(new { Status = "Error" });
}
private static string GetFileName(IFormFile file) => file.ContentDisposition.Split(';')
.Select(x => x.Trim())
.Where(x => x.StartsWith("filename="))
.Select(x => x.Substring(9).Trim('"'))
.First();
}
Run Code Online (Sandbox Code Playgroud)
FileUpload尚未在MVC6中实现,请参阅此问题,以及相关问题,例如此状态.
您可以从JavaScript 发布XMLHttpRequest并使用以下代码捕获它:
public async Task<IActionResult> UploadFile()
{
Stream bodyStream = Context.Request.Body;
using(FileStream fileStream = File.Create(string.Format(@"C:\{0}", fileName)))
{
await bodyStream.CopyToAsync(fileStream);
}
return new HttpStatusCodeResult(200);
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果您看到链接的问题,他们现在已经关闭.您现在可以使用更常规的方式在MVC6中上传文件.
| 归档时间: |
|
| 查看次数: |
15734 次 |
| 最近记录: |