【问题标题】:Image Uploading in Dot net core Web API点网核心 Web API 中的图像上传
【发布时间】:2021-05-13 09:45:27
【问题描述】:

我是 dot net core 的新手。 如何将图像上传、编辑和删除到 dot net core WEB API? 我应该怎么做,逐步添加/编辑或删除图像。 我没有 wwwroot 文件夹。 我需要上传员工头像,如果我删除员工,员工头像也应该被删除。

这是我的 EmployeeController.cs 文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EmployeeWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting.Internal;

namespace EmployeeWebApi.Controllers
{
    [Route("api/[Controller]")]
    [ApiController]
    public class EmployeeController:ControllerBase
    {
        private readonly EmployeeDbContext _context; 
        public EmployeeController(EmployeeDbContext context)
        {
            _context = context;
        }

        //GET: api/Emplyeee
        [HttpGet]
        public async Task<List<Employee>> GetAllEmployees(){
           
            var employees = await _context.Thanusiga_Employees.ToListAsync();

            return employees;
        }

        //GET: api/Employee/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Employee>> GetEmployee(int id){
            var employee = await _context.Thanusiga_Employees.FindAsync(id);

            if( employee == null){
                return NotFound();
            }

            return employee;
        }

        //POST: api/Employee
        [HttpPost]
        public async Task<ActionResult<Employee>> PostEmployee(Employee employee){
            _context.Thanusiga_Employees.Add(employee);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetEmployee), new {id = employee.Id}, employee);

        }

        //PUT: api/Employee/3
        [HttpPut("{id}")]
        public async Task<IActionResult> PutEmployee(int id, Employee employee){
            if(id != employee.Id){
                return BadRequest();
            }

            _context.Entry(employee).State = EntityState.Modified;

            try{
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException){
                if(!EmployeeExists(id)){
                    return NotFound();
                }
                else{
                    throw;
                }
            }
            return NoContent();
        }

        private bool EmployeeExists(int id)
        {
            throw new NotImplementedException();
        }


        //DELETE: api/Employee/3
        [HttpDelete("{id}")]
        public async Task<ActionResult<Employee>> DeleteEmployee(int id){
            var employee = await _context.Thanusiga_Employees.FindAsync(id);
            if(employee == null){
                return NotFound();
            }
            _context.Thanusiga_Employees.Remove(employee);
            await _context.SaveChangesAsync();

            return employee;
        }


    }

}

提前致谢

【问题讨论】:

  • 嗨@hanushi,请问回复是否解决了问题或者这个帖子有什么更新吗?如果答案解决了问题,请接受 - 请参阅What should I do when someone answers my question。如果您对我的回复有任何疑问,请随时告诉我。

标签: c# asp.net-core-webapi


【解决方案1】:

要通过Asp.net核心API将图像文件上传到数据库,首先我们应该使用IFormFile将图像文件从客户端发送到API动作方法。然后,将IFormFile 复制到一个流中,并将其作为字节数组保存在数据库中。

您可以参考以下示例,在此示例中,我使用两个 View 模型让用户输入值并将数据返回给客户端。

在 Web API 中,使用以下模型:

//the view model, used to transfer the user entered value and the image file.
public class FileViewModel
{
    public string Name { get; set; }
    public IFormFile File { get; set; }
    public List<IFormFile> Files { get; set; }
}

//Assume this is your Employee table, and you could also add a property to store the image name.
public class AppFile   
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Content { get; set; } //byte array to store the image data.        
}
//this model is used to return the record to client, include the image source, then display the image in the view page.
public class ReturnData
{
    public string Name { get; set; }
    public string ImageBase64 { get; set; }
}

上传动作方法:

[HttpPost]
[Route("upload")]
public async Task<IActionResult> UploadImageProfile([FromForm]FileViewModel fileviewmodel)
{
    if (ModelState.IsValid)
    {
        using (var memoryStream = new MemoryStream())
        {
            await fileviewmodel.File.CopyToAsync(memoryStream);

            // Upload the file if less than 2 MB
            if (memoryStream.Length < 2097152)
            {
                //create a AppFile mdoel and save the image into database.
                var file = new AppFile()
                {
                    Name = fileviewmodel.Name,
                    Content = memoryStream.ToArray()
                };

                _context.AppFiles.Add(file);
                _context.SaveChanges();
            }
            else
            {
                ModelState.AddModelError("File", "The file is too large.");
            }
        }

        var returndata = _context.AppFiles
            .Where(c => c.Name == fileviewmodel.Name)
            .Select(c => new ReturnData()
            {
                Name = c.Name,
                ImageBase64 = String.Format("data:image/png;base64,{0}", Convert.ToBase64String(c.Content))
            }).FirstOrDefault();
        return Ok(returndata);
    }
    return Ok("Invalid");
}

然后,在MVC视图页面中,使用JQuery Ajax上传表单数据并预览图片。

@model WebApplication6.Models.FileViewModel

<div class="row">
    <div class="col-md-4">
        <form id="myform" enctype="multipart/form-data" asp-action="FileUpload">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <dl>
                    <dt>
                        <label asp-for="File"></label>
                    </dt>
                    <dd>
                        <input asp-for="File" type="file">
                    </dd>
                </dl>

            </div>
            <div class="form-group"> 
                <input type="button" id="btnsubmit" value="Ajax Create" class="btn btn-primary"  />
            </div>
        </form>
    </div>
</div>
<div id="imagepreview">

</div>

@section Scripts{ 
<script>
    $(function () {
        $("#btnsubmit").click(function () {
            var fd = new FormData();
            fd.append('name', $("#Name").val())
            fd.append('file', $('#File')[0].files[0]);

            $.ajax({
                url: "/api/todo/upload",
                data: fd,
                processData: false,
                contentType: false,
                method: "post",
                headers: {
                    RequestVerificationToken:
                        $('input:hidden[name="__RequestVerificationToken"]').val()
                },
                success: function (response) { 
                    $("#imagepreview").append("<img src='" + response.imageBase64 + "' alt='' class='img-fluid'>");
                }
            })
        });
    });
</script>
}

结果如下:

有关上传文件的更多详细信息,请参阅:Upload files in ASP.NET Core

要编辑员工的形象,首先要根据员工主键找到员工,然后,获取员工信息。在编辑页面,你可以添加一个文件类型元素来选择一个新的图像,然后参考上面的代码来编辑员工。

最后,如果你要删除一个Employee,由于图像数据在Employee表中,删除Emploee,它会自动删除图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多