c# - 点网核心 Web API 中的图像上传
问题描述
我是点网核心的新手。如何将图像上传、编辑和删除到 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;
}
}
}
提前致谢
解决方案
要通过 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>
}
结果是这样的:
有关上传文件的更多详细信息,请参阅:在 ASP.NET Core 中上传文件。
要编辑员工的形象,首先要根据员工主键找到员工,然后,获取员工信息。在 Edit 页面中,您可以添加一个文件类型元素来选择一个新图像,然后将上述代码引用到 Edit Employee。
最后,如果你想删除一个Employee,由于图像数据在Employee表中,删除Emploee,它会自动删除图像。
推荐阅读
- spring - 删除 OneToOne 关系中的对象 ConstraintViolationException
- php - 一旦用户在 php 中使用,令牌必须从表中删除
- javascript - 在另一行之前和之后追加行
- r - 在R中,矩阵的子集行得到一个列表
- gcc - ELF 文件中相同源代码的不同入口点
- powershell - 删除后 Powershell SVN 提交
- jsxgraph - 使用 jessiecode 更新 jsxgraph 对象
- php - 在 PHP 中集成 Coinbase Commerce
- java - 卡夫卡交易失败,但无论如何提交偏移
- arduino - Arduino 和 ESP8266-01 通信问题