如何将模型值 IFormFile 从视图传递到控制器 On Change 事件
How to pass model value IFormFile from view to controller On Change event
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
<div class="col">
<ul class="list-group mt-3">
@if (Model.Products != null && Model.Products.Count > 0)
{
@for (int i = 0; i < Model.Products.Count; i++)
{
<li class="list-group-item">
<input asp-for="@Model.Products[i].IsChecked" type="checkbox" />
<label asp-for="@Model.Products[i].ProductId"> @Model.Products[i].ProductName</label>
<input type="hidden" asp-for="@Model.Products[i].ProductId"/>
<input type="hidden" asp-for="@Model.Products[i].ProductName" asp-route-productId/>
<div class="uploadFile float-end">
<label class="file-label">
<img class="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
</label>
<input asp-for="@Model.Products[i].ProductImage" asp-for-ProductId="@Model.Products[i].ProductId" type="file" class="productImage" onchange="getImage(this.value);" style="visibility:none; display:none"/>
</div>
</li>
}
}
else
{
<li class="list-group-item">nodata</li>
}
</ul>
</div>
[.js]
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
[controller method]
[HttpPost]
public async Task<JsonResult> AddPhoto(DailySelectedProductViewModel dataModel)
{
IFormFile file = dataModel.ProductImage;
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
}
return Json(file.FileName);
}
在这里,我从视图中获取了我的 ViewModel 中的空值,我有一个元素列表,每个元素都选择了文件 (innput type="file")。在选择任何图像时,On Change 事件会触发,然后它会调用控制器方法,但我被困住了,我如何才能将模型值从视图发送到控制器。 productImage 的数据类型也为 IFormFile。因此,在将它从视图传递到控制器后,我如何将其转换为字节或使用“image”类型的 sqlserver 列直接保存它?
请帮我解决这个问题!
谢谢:)
尝试使用 data:form-data, 然后你可以将带有值的键插入到这个 FormData() 对象中您可以将其传输到您的控制器。如果您想了解更多关于 FormData() 的信息,请阅读 here
下面是工作demo,您可以参考一下:
controller.cs:
public class AAController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> uploader(UploadVm model)
{
return this.View();
}
}
Index.cshtml:
<form id="form" name="form" action="uploader" enctype="multipart/form-data" method="post">
<div class="buttons">
<div class="upload-button">
<input id="id" type="text" />
<input id="type" type="text" />
<input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
</div>
</div>
</form>
@section Scripts{
<script>
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
//Add the input element values
formData.append("Type", $("#type").val());
formData.append("Id", $("#id").val());
$.ajax(
{
url: "/AA/uploader",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("Files Uploaded!");
}
}
);
}
</script>
}
Uploader.cs:
public class UploadVm
{
public string Type { set; get; }
public string Id { set; get; }
public IList<IFormFile> Files { get; set; }
}
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
<div class="col">
<ul class="list-group mt-3">
@if (Model.Products != null && Model.Products.Count > 0)
{
@for (int i = 0; i < Model.Products.Count; i++)
{
<li class="list-group-item">
<input asp-for="@Model.Products[i].IsChecked" type="checkbox" />
<label asp-for="@Model.Products[i].ProductId"> @Model.Products[i].ProductName</label>
<input type="hidden" asp-for="@Model.Products[i].ProductId"/>
<input type="hidden" asp-for="@Model.Products[i].ProductName" asp-route-productId/>
<div class="uploadFile float-end">
<label class="file-label">
<img class="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
</label>
<input asp-for="@Model.Products[i].ProductImage" asp-for-ProductId="@Model.Products[i].ProductId" type="file" class="productImage" onchange="getImage(this.value);" style="visibility:none; display:none"/>
</div>
</li>
}
}
else
{
<li class="list-group-item">nodata</li>
}
</ul>
</div>
[.js]
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
[controller method]
[HttpPost]
public async Task<JsonResult> AddPhoto(DailySelectedProductViewModel dataModel)
{
IFormFile file = dataModel.ProductImage;
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
}
return Json(file.FileName);
}
在这里,我从视图中获取了我的 ViewModel 中的空值,我有一个元素列表,每个元素都选择了文件 (innput type="file")。在选择任何图像时,On Change 事件会触发,然后它会调用控制器方法,但我被困住了,我如何才能将模型值从视图发送到控制器。 productImage 的数据类型也为 IFormFile。因此,在将它从视图传递到控制器后,我如何将其转换为字节或使用“image”类型的 sqlserver 列直接保存它?
请帮我解决这个问题! 谢谢:)
尝试使用 data:form-data, 然后你可以将带有值的键插入到这个 FormData() 对象中您可以将其传输到您的控制器。如果您想了解更多关于 FormData() 的信息,请阅读 here
下面是工作demo,您可以参考一下:
controller.cs:
public class AAController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> uploader(UploadVm model)
{
return this.View();
}
}
Index.cshtml:
<form id="form" name="form" action="uploader" enctype="multipart/form-data" method="post">
<div class="buttons">
<div class="upload-button">
<input id="id" type="text" />
<input id="type" type="text" />
<input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
</div>
</div>
</form>
@section Scripts{
<script>
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
//Add the input element values
formData.append("Type", $("#type").val());
formData.append("Id", $("#id").val());
$.ajax(
{
url: "/AA/uploader",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("Files Uploaded!");
}
}
);
}
</script>
}
Uploader.cs:
public class UploadVm
{
public string Type { set; get; }
public string Id { set; get; }
public IList<IFormFile> Files { get; set; }
}