簡體   English   中英

如何使用 .NET Core API 將圖像文件上傳到數據庫?

[英]How to upload image files to database with .NET Core API?

我正在創建一個用戶可以發布的應用程序,比如論壇。 我正在嘗試將圖像和文本加載到數據庫中,為此,我有兩個表,它們都通過 id 相關聯。 我想出了如何加載文本內容,但我真的不知道如何對圖像內容做同樣的事情。 我正在使用 MVC 視圖和它各自的 controller 來使用 API。

我正在使用的 model:

public class ForumThemeModel
{
    public ForumThemeModel()
    {
        Themes = new HashSet<Theme>();
    }

    //forum table
    [Key]
    public int IdForum { get; set; }
    public string PostTittle { get; set; }

    //theme table
    public int? Idtheme { get; set; }
    public string TextContent { get; set; }
    public int? IdForum { get; set; }
    public IFormFile ContentFile { get; set; } //where the image will be stored
    public string FileNameA { get; set; }
    public string FileType { get; set; }
}

進行帖子創建的 API controller :

    [HttpPost]
    [Consumes("multipart/form-data")]
    [Route("createPost")]
    public async Task<IActionResult> createPost([FromBody]ForumThemeModel model)
    {
        Forum forum = new Forum();

        Theme theme = new Theme();

        var fileName = Path.GetFileName(model.FileNameA);
        var fileExt = Path.GetExtension(fileName);
        var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExt);

        using(var target = new MemoryStream())
        {
            await model.ContentFile.CopyToAsync(target);
            theme.ContentFile = target.ToArray();
        }

        forum.PostTittle = model.PostTittle;
        theme.FileNameA = newFileName;
        theme.FileType = fileExt;

        var postTittle = new SqlParameter("@postTittle", forum.PostTittle);
        var textContent = new SqlParameter("@textContent", theme.TextContent);
        var content_file = new SqlParameter("@content_file", theme.ContentFile);
        var file_name_a = new SqlParameter("@file_name_a", theme.FileNameA);
        var FileType = new SqlParameter("@FileType", theme.FileType);

        //saves everything to database

        return Ok();
    }

使用了 API 的 MVC controller:

    [HttpPost]
    public IActionResult createPost(ForumThemeModel model)
    {
        HttpClient hc = new HttpClient();
        hc.BaseAddress = new Uri("https://localhost:44325/api/Users");

        var userPost = hc.PostAsJsonAsync<ForumThemeModel>("Users/createPost", model);

        userPost.Wait();
        
        //do something when the resquest result is successful
    }

MVC controller 的視圖:

@model Huerbog.Models.Request.ForumThemeModel

@{
     ViewData["Title"] = "CreatePost";
 }
 <hr />
 <div class="row">
    <div class="col-12 col-md-9">
        <form enctype="multipart/form-data" asp-action="createPost">
           <div asp-validation-summary="ModelOnly" class="text-danger"></div>

           <div class="form-group h4">
              <label asp-for="PostTittle" class="control-label">Tittle</label>
              <input asp-for="PostTittle" class="form-control" />
              <span asp-validation-for="PostTittle" class="text-danger"></span>
           </div>
           <div class="form-group h4">
              <label asp-for="Content" class="control-label">Content of the post</label>
              <textarea rows="5" asp-for="Content" class="form-control"></textarea>
              <span asp-validation-for="Content" class="text-danger"></span>
           </div>
           <div class="form-group h4">
              <label asp-for="ContentFile" class="control-label">Imagen:</label><br />
              <input class="form-control-file" multiple asp-for="ContentFile" type="file" />
           </div>
           <div class="form-group h4">
              <input type="submit" value="Create post" class="btn btn-primary" />
           </div>
         </form>
    </div>
 </div>

因此,我已閱讀有關上傳圖像或文件的信息,它表明在數據庫中上傳圖像或不同類型的文件時,屬性enctype = "multipart / form-data"應該存在於視圖中,因為該屬性會發生兩件事: the first is that when I leave the attribute in the view the MVC controller does not use the API controller, but the model receives the information from the file or image such as the name, the file type, etc. The second is when I remove the attribute from the view, in this case the MVC controller makes use of the API controller, but the model does not contain anything regarding the file or the image. 在這兩種情況下,文本內容都由 model 接收,但由於缺少有關圖像的信息,它也沒有被數據庫保存。

我不太確定enctype = "multipart / form-data"屬性是否是主要原因,但正如我之前所說,在圖片上傳之前,文本內容運行良好,並且enctype = "multipart / form-data"不存在。

我在 img 上傳上停留了一段時間,真的我不知道該怎么做,感謝任何幫助。

public IFormFile ContentFile { get; set; }

首先,請注意PostAsJsonAsync方法會將 model 數據序列化為 JSON 然后發送到請求正文中,這對序列化FormFile沒有意義,會導致錯誤。

為了實現使用 MVC controller 動作中的 API 來上傳文件和其他數據的需求,您可以參考以下示例代碼。

[HttpPost]
public async Task<IActionResult> CreatePost(ForumThemeModel model)
{
    var formContent = new MultipartFormDataContent();

    formContent.Add(new StringContent(model.PostTittle), "PostTittle");

    //...
    //for other properties, such as FileNameA, FileType etc
    //...

    formContent.Add(new StreamContent(model.ContentFile.OpenReadStream()), "ContentFile", Path.GetFileName(model.ContentFile.FileName));


    HttpClient hc = new HttpClient();
    hc.BaseAddress = new Uri("https://localhost:44325/api/Users/");

    var userPost = await hc.PostAsync("createPost", formContent);

    //...

API 動作

public async Task<IActionResult> createPost([FromForm]ForumThemeModel model) 
{
    //...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM