'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);
}
Here, I am getting null value in my ViewModel from view, I have of one list of elements and each elements have choose file (innput type="file") with them. on choosing any image On Change event get trigger and then it calls the controller method but i am getting stuck that how can i send the model value from view to controller. also the productImage is of datatype = IFormFile. so after getting it pass from view to controller how can i convert it into bytes or does sqlserver column with "image" type save it directly ?
please help me with this issue! Thank you :)
Solution 1:[1]
Try to use data:form-data, and you can insert key with values into this FormData() obj then you can transmit it to your controller. If you want to know more about FormData() then read here
Below is a work demo,you can refer to it:
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; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |