gpt4 book ai didi

javascript - 如何将图像文件列表保存在 var [] 中并将它们立即发送到 Controller

转载 作者:行者123 更新时间:2023-11-28 03:44:41 25 4
gpt4 key购买 nike

我需要将图像文件数组发送到 Controller 。下面我已将一个文件发送到 Controller ,但我需要发送图像文件列表。

我的 Controller :

public async Task<IActionResult> AddImage(string emailid , List<IFormFile> imagefile)
{
ImageUpload img=new ImageUpload();
var emailId = feedBackContext.UserMasters.FirstOrDefault(m=>m.Email==emailid);
foreach (var item in imagefile)
{
if (item.Length > 0)
{
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
img.imagefile = stream.ToArray();
}
}

}

img.EmailID = emailId.UserMasterID;
var existimage = feedBackContext.ImageUpload.FirstOrDefault(m => m.EmailID == emailId.UserMasterID);
if (existimage == null)
{
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
else
{
feedBackContext.ImageUpload.Remove(existimage);
feedBackContext.SaveChanges();
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
}

我的 JavaScript 文件:
(我需要将图像文件数组发送到 Controller ,就像传递数组一样)

function sendArr(form)
var []=imgarr;
{

$.ajax(
{
type: "POST",
traditional: true,
url: form.action,
data: { dataList: arr, imageList: imgarr },
dataType: "json",
success: function (asd) {
document.getElementById("QuestionDescription").value = "";
document.getElementById("AnswerDescription").value = "";
count = 0;
$('#demo').remove();

document.getElementById("QuestionDescription").focus();
window.location.href = '';
}
});
}
}

我的表格::

<script>
function addAnswer() {

imgarr[count] = document.getElementById('imagefile').value;

}
</script>

<form asp-action="AddImage">
<input type="file" id="imagefile" name="imagefile" />
</form>

如果您对此有所了解,请帮助我。

最佳答案

考虑一下您的表单看起来与此类似:

<form action="" method="post" enctype="multipart/form-data">

<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />

<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />

<input type="submit" />
</form>

Controller :您需要使用IEnumerable<HttpPostedFileBase>

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

files变量指的是表单字段中的名称属性。

如果您愿意,您还可以将变量填充到模型中。

示例取自 here

关于javascript - 如何将图像文件列表保存在 var [] 中并将它们立即发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48616735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com