【问题标题】:How to Upload Files and Save in Database and download another page in ASP.NET Core MVC如何在 ASP.NET Core MVC 中上传文件并保存在数据库中并下载另一个页面
【发布时间】:2022-08-19 23:29:32
【问题描述】:

下载如何以我们上传其存储二进制格式的形式执行功能如何在控制器操作中从二进制文件中检索数据

public IActionResult Index(IFormFile files)
{
        if (files != null)
        {
            if (files.Length > 0)
            {
                // Getting FileName
                var fileName = Path.GetFileName(files.FileName);

                // Getting file Extension
                var fileExtension = Path.GetExtension(fileName);

                // concatenating  FileName + FileExtension
                var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);

                var objfiles = new Files()
                {
                    DocumentId = 0,
                    Name= newFileName,
                    FileType = fileExtension,
                    CreatedOn = DateTime.Now
                };
                
                using (var target = new MemoryStream())
                {
                    files.CopyTo(target);
                    objfiles.DataFiles = target.ToArray();
                }

                _context.Files.Add(objfiles);
                _context.SaveChanges();
            }
        }

        return View();
}

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    下载如何以我们上传的形式执行功能 存储二进制格式如何从二进制文件中检索数据 控制器动作

    你的意思是要将文件上传到数据库,然后从数据库中下载指定的文件?

    如您所说,要将文件上传到数据库中,您需要使用 IFormFile。像这样的代码:

    public class Product
    {
        [Key]
        public int ProId { get; set; }
        public string ProName { get; set; }
        public string ProImageName { get; set; }
        public byte[] ProImageContent { get; set; }
        public string ProImageContentType { get; set; }
        //you can add another properties
    }
    

    上传方式:

        [HttpPost]
        public async Task<IActionResult> CreateAsync(ProductViewModel product)
        {
            if (ModelState.IsValid)
            {
                //save image to database.
                using (var memoryStream = new MemoryStream())
                {
                    await product.FormFile.CopyToAsync(memoryStream);
    
                    // Upload the file if less than 2 MB
                    if (memoryStream.Length < 2097152)
                    {
                        //Convert the View 
                        var file = new Product()
                        {
                            ProImageName = product.FormFile.FileName,
                            ProImageContent = memoryStream.ToArray(),
                             
                            ProImageContentType = product.FormFile.ContentType,
    
                            ProName = product.Name
                        };
                        _dbcontext.Products.Add(file);
    
                        await _dbcontext.SaveChangesAsync();
                    }
                    else
                    {
                        ModelState.AddModelError("File", "The file is too large.");
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View();
        }
    

    然后,要下载文件,在索引列表中,您可以添加带有主键的超链接,如下所示:

    @Html.ActionLink("DownLoad Image", "DownloadImage", new {  id=item.ProId })
    

    整个索引页代码:

    @model List<MVC6App.Data.Product>
    
    @{
        ViewData["Title"] = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    } 
    <p>
        <a asp-action="Create">Create New</a>
    </p>
    
    <table class="table">
        <thead>
            <tr>
                <th>
                    ProId
                </th>
                <th>
                    ProName
                </th>
                <th>
                    ProImageName
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @if (Model != null && Model.Count > 0)
            {
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.ProId)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.ProName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.ProImageName)
                        </td>
                        <td>
                            @Html.ActionLink("DownLoad Image", "DownloadImage", new {  id=item.ProId })
                            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                        </td>
                    </tr>
                }
            }
            else
            {
                <tr><td colspan="4"> empty</td></tr>
            }
        </tbody>
    </table>
    

    控制器索引操作:

        public IActionResult Index()
        {
            var result = _dbcontext.Products.ToList();
            return View(result);
        }
    

    然后,在 DownLoadImage 动作方法中,根据主键查询数据库并获取图像/文件内容,然后返回 File 结果以下载文件:

        public IActionResult DownloadImage(int id)
        {
            byte[] bytes;
            string fileName, contentType;
            var item = _dbcontext.Products.FirstOrDefault(c => c.ProId == id);
    
            if(item != null)
            { 
                fileName = item.ProImageName;
    
                contentType = item.ProImageContentType;
                bytes = item.ProImageContent;
                return File(bytes, contentType, fileName);
            }
            return Ok("Can't find the Image");
        }
    

    结果是这样的:

    【讨论】:

      【解决方案2】:
      • 您好先生,非常感谢您,我明白了,但是在下载时我需要 帮助在此处输入代码,因为当我单击下载时,它正在运行 其他条件

        下载 :

        公共 IActionResult 下载图像(int id) { 字节[] 字节; 字符串文件名,内容类型; var item = _auc.Files.FirstOrDefault(c => c.DocumentId == id);

             if (item != null)
             {
                 fileName = item.Name;
        
                 contentType = item.FileType;
                 bytes = item.DataFiles;
                 return File(bytes, contentType, fileName);
             }
             return Ok("Can't find the File");
         }
        }
        

        在 Controller for Create [上传文件没问题我可以看到我的文件 ) 在数据库中

        上传以上代码enter image description here

      【讨论】:

      • but when in download i need help enter code here ir because when I click download in it's going else condition,可以在DownLoadImage方法中设置断点,检查id的值,是否正确,是否与数据库中的DocumentId相等?也许id是0,所以在数据库中找不到文档。在这种情况下,您可以查看下载超链接,问题可能与它没有添加 id 参数成功有关,尝试共享这部分代码。
      • 嗨,先生,是的,当我检查“var item auc files getting null values but in method I get I'd and are using both I need to fetch two model data in a single view upload is store in created以索引操作方法在下载中检索动作我没有使用asyc,请尝试帮助我,您能否按照示例google.com/amp/s/tutexchange.com/…检索存储二进制文件我请点击此链接先生,我需要基于此上传文件的下载路径
      【解决方案3】:
      • 嗨,先生,请在下面找到所有代码

             enter code here
        
         //
        
        
                 private readonly ApplicationUser _auc;
                 private IConfiguration _config;
                 CommonHelpers _helpers;
        
                 public ApplicationController(IConfiguration config, ApplicationUser auc)
                 {
                     _config = config;
                     _helpers = new CommonHelpers(_config);
                     _auc = auc;
                 }
        
        
        
                 // GET: ApplicationController
                 public ActionResult Index()
                 {
                     var model = new List<Application>();
        
                     using (SqlConnection con = new SqlConnection("test"))
                     {
        
                         con.Open();
                         string sql = "SELECT * FROM [Application]";
                         SqlCommand cmd = new SqlCommand(sql, con);
                         cmd.CommandType = System.Data.CommandType.Text;
                         SqlDataReader rdr = cmd.ExecuteReader();
                         while (rdr.Read())
                         {
                             var App = new Application();
                             App.Id = Convert.ToInt32(rdr["id"]);
                             App.ApplicationName = rdr["ApplicationName"].ToString();
                             App.Technology = rdr["Technology"].ToString();
        
                             App.TeamMembers = rdr["TeamMembers"].ToString();
        
                             model.Add(App);
                         }
        
                         con.Close();
                         return View(model);
        
                     }
        
                         return View();
                 }
        
                 // GET: ApplicationController/Details/5
                 public ActionResult Details(int id)
                 {
                     using (SqlConnection con = new SqlConnection("test"))
                     {
                         var model = new List<Application>();
                         con.Open();
                         string sql = "SELECT * FROM [Application] Where id =@id";
                         SqlCommand cmd = new SqlCommand(sql, con);
                         cmd.Parameters.AddWithValue("@id", id);
                         cmd.CommandType = System.Data.CommandType.Text;
                         SqlDataReader rdr = cmd.ExecuteReader();
                         while (rdr.Read())
                         {
                             var App = new Application();
                             App.Id = Convert.ToInt32(id.ToString());
                             App.ApplicationName = rdr["ApplicationName"].ToString();
                             App.Technology = rdr["Technology"].ToString();
                             App.AddDatabase = rdr["AddDatabase"].ToString();
                            ;
        
                             model.Add(App);
        
                         }
        
                         con.Close();
                         return View(model);
        
        
                     }
                     return View();
                 }
        
        
                 // GET: ApplicationController/Create
                 public ActionResult Create()
                 {
                     return View();
                 }
        
                 // POST: ApplicationController/Create
                 [HttpPost]
                 [ValidateAntiForgeryToken]
                 public ActionResult Create(Application db, List<IFormFile> files)
                 {
                     try
                     {
                         using (SqlConnection con = new SqlConnection("test"))
                         {
        
        
                             string query = $"Insert into [Application] (ApplicationName,Technology,AddDatabase,Incharge";
                             SqlCommand cmd = new SqlCommand(query, con);
                             cmd.Parameters.AddWithValue("@ApplicationName",db.ApplicationName);
                             cmd.Parameters.AddWithValue("@Technology", db.Technology);
                             cmd.Parameters.AddWithValue("@AddDatabase", db.AddDatabase);
                             cmd.Parameters.AddWithValue("@Incharge", db.Incharge);
        
        
        
                                 if (files != null)
                             {
                                 foreach (var file in files)
                                 {
        
                                     if (file.Length > 0)
                                     {
                                         //Getting FileName
                                         var fileName = Path.GetFileName(file.FileName);
                                         //Getting file Extension
                                         var fileExtension = Path.GetExtension(fileName);
                                         // concatenating  FileName + FileExtension
                                         //var newFileName = String.Concat((Guid.NewGuid()), fileExtension);
        
                                         var objfiles = new Files()
                                         {
                                             DocumentId = 0,
                                             Name = fileName,
                                             FileType = fileExtension,
                                             CreatedOn = DateTime.Now
                                         };
        
                                         var filepath =
             new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),
         "wwwroot", "pdf")).Root + $@"\{fileName}";
        
                                         using (FileStream fs = System.IO.File.Create(filepath))
                                         {
                                             file.CopyTo(fs);
                                             fs.Flush();
                                         }
        
        
        
                                         using (var target = new MemoryStream())
                                         {
                                             file.CopyTo(target);
                                             objfiles.DataFiles = target.ToArray();
                                         }
        
        
        
        
                                         _auc.Files.Add(objfiles);
                                         _auc.SaveChanges();
        
                                     }
                                 }
                             }
        
        
                             con.Open();
                             cmd.ExecuteNonQuery();
                             con.Close();
                             return RedirectToAction("Index");
                         }
        
                     }
                     catch
                     {
                         return View();
                     }
        
                     return View();
                 }
        
                 // model  controller
        
         appication user enity 
        
          public class ApplicationUser: DbContext
             {
                 public ApplicationUser(DbContextOptions<ApplicationUser> options) : base(options)
                 {
        
                 }
                 public DbSet<Users> Users { get; set; }
                 public DbSet<EmpFileMst> EmpFileMst { get; set; }
                 public DbSet<Application> Application { get; set; }
        
                 public DbSet<Files> Files { get; set; }
             } }
        
        
         view model create(upload )
        
        
         <div class="form-group">
                         <label asp-for="CompletionDate" class="control-label"></label>
                         <input asp-for="CompletionDate" class="form-control" />
                         <span asp-validation-for="CompletionDate" class="text-danger"></span>
                     </div>
                     <div class="form-group">
                         <label asp-for="Note" class="control-label"></label>
                         <input asp-for="Note" class="form-control" />
                         <span asp-validation-for="Note" class="text-danger"></span>
                     </div>
                     <div class="form-group">
                         <label asp-for="TeamMembers" class="control-label"></label>
                         <input asp-for="TeamMembers" class="form-control" />
                         <span asp-validation-for="TeamMembers" class="text-danger"></span>
                     </div>
                       <div class="form-group">
        
                             <label class="control-label">Requirements Document: </label>
                             <input class="form-control" name="files" type="file" multiple="multiple" placeholder="Upload Document" 
         value="Upload"/><br />
        
        
                     </div>
        
        
        
         details index  view 
        
         @model List<Application>
        
          @foreach(var app in Model)
                             {
                                 <tr>
                                     <td>@app.Id</td>
                                      <td>@app.ApplicationName,@app.AddDatabase ....</td>                  
        
                                     <td>@app.Note</td>
        
        
                                     <td><a asp-action="Details" asp-route-id="@app.Id" class="btn btn-primary">View More</a></td>
                                 </tr>
                             }
        

      【讨论】:

        猜你喜欢
        • 2021-04-01
        • 1970-01-01
        • 2017-01-04
        • 2015-08-02
        • 1970-01-01
        • 2017-06-28
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        相关资源
        最近更新 更多