添加照片和模型

14 浏览
0 Comments

添加照片和模型

我是asp.net core的新手。在使用模型上传文件(图片)时遇到了问题。

视图模型:

namespace WebApplication1.ViewModels
{
    public class HotelViewModel
    {
        public String NomHotel { get; set; }
        public String NomAgence { get; set; }
        public String Filepath{ get; set; }
    }
}

这是cshtml:

@model WebApplication1.ViewModels.HotelViewModel

controller="Hotel" asp-action="Hotel">

使用此表单上传一个或多个文件:

这是控制器:

[HttpPost]
public IActionResult Hotel(HotelViewModel mod)
{
    Hotel hotel = new Hotel
    {
        NomAgence = mod.NomAgence,
        NomHotel = mod.NomHotel
    };
    var newFileName = string.Empty;
    if (HttpContext.Request.Form.Files != null)
    {
        var fileName = string.Empty;
        string PathDB = string.Empty;
        var files = HttpContext.Request.Form.Files;
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                //获取文件名
                fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                //分配唯一文件名(Guid)
                var myUniqueFileName = Convert.ToString(Guid.NewGuid());
                //获取文件扩展名
                var FileExtension = Path.GetExtension(fileName);
                //连接文件名和文件扩展名
                newFileName = myUniqueFileName + FileExtension;
                //将两个字符串组合为路径
                fileName = Path.Combine(_environment.WebRootPath, "HotelImg") + $@"\{newFileName}";
                //如果要将文件夹路径存储在数据库中
                PathDB = "demoImages/" + newFileName;
                hotel.Piscine = newFileName;
                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
        }
    }
    IH.Create(hotel);
    return View();
}

我尝试了不同的代码组合,但是我始终只能获取到文件或模型,而我需要同时获取它们。这是我能给出的最正确的代码,如果不够清晰,很抱歉。

0