在 .Net 5 中发布带有图像的模型
Posting Model with image in .Net 5
我正在使用 .Net 5 构建 Web API,我有一个包含图像的模型,我想 POST 带有图像的模型将图像保存到文件中系统并将图片路径取入数据库。
假设我们有我们的模型:
public partial class Document
{
public int id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
}
我试过了:
[Route("api/Images")]
public class ImageController : Controller
{
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
var stream = new FileStream(path, FileMode.Create);
file.CopyToAsync(stream);
return Ok(new { length = file.Length, name = file.FileName });
}
catch
{
return BadRequest();
}
}
}
我仍然需要将我的模型与图像文件一起传递。
要通过Asp.net核心API将图像文件上传到数据库,首先,我们应该使用IFormFile
将图像文件从客户端发送到API动作方法。然后,将IFormFile
保存到文件系统中,将图片路径取到数据库中。
您可以参考下面的示例,在这个示例中,我使用视图模型让用户输入值并上传图片。
在 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; }
}
API上传动作方法:
[HttpPost]
[Route("upload")]
public async Task<IActionResult> UploadImageProfile([FromForm] FileViewModel fileviewmodel)
{
if (ModelState.IsValid)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileviewmodel.File.FileName);
var stream = new FileStream(path, FileMode.Create);
await fileviewmodel.File.CopyToAsync(stream);
//create a Document instance, and insert value into database.
return Ok(new { length = fileviewmodel.File.Length, name = fileviewmodel.File.FileName });
}
catch
{
return BadRequest();
}
return Ok("");
}
return Ok("Invalid");
}
然后,在MVC视图页面,使用JQueryAjax上传表单数据和预览图片。
@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>
@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) {
}
})
});
});
</script>
}
结果是这样的:
有关上传文件的更多详细信息,请参阅:Upload files in ASP.NET Core。
我正在使用 .Net 5 构建 Web API,我有一个包含图像的模型,我想 POST 带有图像的模型将图像保存到文件中系统并将图片路径取入数据库。
假设我们有我们的模型:
public partial class Document
{
public int id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
}
我试过了:
[Route("api/Images")]
public class ImageController : Controller
{
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", file.FileName);
var stream = new FileStream(path, FileMode.Create);
file.CopyToAsync(stream);
return Ok(new { length = file.Length, name = file.FileName });
}
catch
{
return BadRequest();
}
}
}
我仍然需要将我的模型与图像文件一起传递。
要通过Asp.net核心API将图像文件上传到数据库,首先,我们应该使用IFormFile
将图像文件从客户端发送到API动作方法。然后,将IFormFile
保存到文件系统中,将图片路径取到数据库中。
您可以参考下面的示例,在这个示例中,我使用视图模型让用户输入值并上传图片。
在 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; }
}
API上传动作方法:
[HttpPost]
[Route("upload")]
public async Task<IActionResult> UploadImageProfile([FromForm] FileViewModel fileviewmodel)
{
if (ModelState.IsValid)
{
try
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileviewmodel.File.FileName);
var stream = new FileStream(path, FileMode.Create);
await fileviewmodel.File.CopyToAsync(stream);
//create a Document instance, and insert value into database.
return Ok(new { length = fileviewmodel.File.Length, name = fileviewmodel.File.FileName });
}
catch
{
return BadRequest();
}
return Ok("");
}
return Ok("Invalid");
}
然后,在MVC视图页面,使用JQueryAjax上传表单数据和预览图片。
@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>
@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) {
}
})
});
});
</script>
}
结果是这样的:
有关上传文件的更多详细信息,请参阅:Upload files in ASP.NET Core。