【问题标题】:ASP .Net Core MVC upload image to SQLiteASP .Net Core MVC 上传图片到 SQLite
【发布时间】:2018-05-16 10:24:31
【问题描述】:

我想上传一个图像文件并将其添加到 SQLite。我是 ASP .Net Core MVC 的新手,我正在学习 https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-mac/?view=aspnetcore-2.0 的教程。 我添加了一个输入字段来在视图中上传文件。但是,我不确定如何继续使用控制器和模型。尝试到处搜索。 一种方法是将图像转换为字节。我不确定在我的情况下我该怎么做。 任何帮助表示赞赏:)

型号:

public class Movie
{
    public int ID { get; set; }

    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }

    // use only letters (white space, numbers and special characters are not allowed). 
    [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
    [Required]
    [StringLength(30)]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$")]
    [StringLength(5)]
    [Required]
    public string Rating { get; set; }

    [DataType(DataType.Upload)]    
      [Display(Name = "Upload File")]    
     // [Required(ErrorMessage = "Please choose file to upload.")]    
    public string Poster { get; set; }   
}

控制器:

public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price,Rating,Poster")] Movie movie)
            {
                if (id != movie.ID)
                {
                    return NotFound();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        _context.Update(movie);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!MovieExists(movie.ID))
                        {
                            return NotFound();
                        }
                        else
                        {
                            throw;
                        }
                    }
                    return RedirectToAction(nameof(Index));
                }
                return View(movie);
            }

查看:

<form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
             <div class="form-group">
                <label asp-for="Rating" class="control-label"></label>
                <input asp-for="Rating" class="form-control" />
                <span asp-validation-for="Rating" class="text-danger"></span>
            </div>

               <div class="form-group">
                <label asp-for="Poster" class="control-label"></label>
                <input type="file" asp-for="Poster" class="form-control" />
                <span asp-validation-for="Poster" class="text-danger"></span>
            </div>



            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>

【问题讨论】:

    标签: asp.net-core-mvc


    【解决方案1】:

    我还没有看到你的代码,但对我来说,我在按钮单击时使用 JavaScript 将图像转换为 base64 进行操作

    var dataURL;
    $("#uploadFileID").change(function() {
        var fileInput = $("#uploadFileID");
            var file = document.querySelector('#uploadFileID').files[0];
            var reader = new FileReader();
            reader.onloadend = function (f) {
                var canvas = document.createElement('CANVAS');
                var ctx = canvas.getContext('2d');
                ctx.drawImage(this, 0, 0);
                dataURL = canvas.toDataURL();
                });
            }
      });
    

    然后使用 ajax post 将其发送到方法并保存到数据库

    【讨论】:

      【解决方案2】:

      这是上传文件https://github.com/Sagardip/studentapp的代码

      public string Upload(IFormFile file)
          {
              var uploadDirecotroy = "uploads/";
              var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);
      
              if (!Directory.Exists(uploadPath))
                  Directory.CreateDirectory(uploadPath);
      
              var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
              var filePath = Path.Combine(uploadPath, fileName);
      
              using (var strem = File.Create(filePath))
              {
                  file.CopyTo(strem);
              }
              return fileName;
          }
      

      【讨论】:

        猜你喜欢
        • 2021-09-22
        • 1970-01-01
        • 2019-07-10
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2011-02-22
        相关资源
        最近更新 更多