如何在 MVC 6 中的 vNext 下上传文件?

2023-11-24

在 MVC 5 中我曾经这样做过:

var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
var file = (HttpPostedFileBase)context.Request.Files[0];

现在,这些在 MVC 6 的 vNext 中不可用。如何从请求中获取文件?


下面的答案是关于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();

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MVC 6 中的 vNext 下上传文件? 的相关文章

随机推荐