ASP .Net Core MVC将图像上传到SQLite

时间:2018-05-16 10:24:32

标签: asp.net-core-mvc

我想上传图片文件并将其添加到SQLite。我是ASP .Net Core MVC的新手,我跟随https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-mac/?view=aspnetcore-2.0的教程。 我添加了一个输入字段来上传视图中的文件。但是,我不确定如何继续使用Controller和Model。到处搜寻。 一种方法是将图像转换为字节。我不知道在我的情况下我怎么能这样做。 任何帮助赞赏:)

型号:

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>

2 个答案:

答案 0 :(得分:0)

我还没有看到你的代码,但对我来说,我在按钮上的操作点击使用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将其发送到方法并将其保存到数据库

答案 1 :(得分:0)

这是上传文件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;
    }