【发布时间】:2019-07-04 03:26:21
【问题描述】:
我正在尝试通过 ajax 向控制器发送 FormData 来保存文件,问题是即使我使用 FormData 函数将所有变量转换为一种形式,我的 ajax 也无法正常工作。
我尝试使用表单,但在表格中,我无法使用表单标签,因为我的按钮在另一个 td 中。当我将它用于整个表时,它也不起作用,我创建了FormData,我在其中附加了所有变量,其余变量都在工作,但图像没有。
index.cshtml:
<tr class="form" style="display:none">
<td class="name">
<input type="text" name="Jméno" value="" />
</td>
<td class="price">
<input type="number" name="Cena" value="" />
</td>
<td class="quantity">
<input type="number" name="Mnozstvi" value="" />
</td>
<td class="image">
<input type="file" id="fileOne" name="fileOne" runat="server" />
</td>
<td>
<button class="FirstSave" type="button" id="btnUpload">Uložit</button>
<button class="getBack">Zahodit</button>
</td>
</tr>
这是我的 JavaScript
$(".FirstSave").click(function () {
let file = document.getElementById('fileOne').file;
let form = new FormData;
form.append('Image', file);
form.append('Name', name);
form.append('Price', price);
form.append('Quantity', quantity);
$.ajax({
url: "Insert",
method: "POST",
cache: false,
processData: false,
data: form,
});
})
产品获取器和设置器
public class Product
{
public string Name { get; set; }
public int Price { get; set; }
public int Quantity { get; set; }
public string ImageUrl { get; set; }
public HttpPostedFileBase Image { get; set; }
}
产品控制器
[HttpPost]
public ActionResult Insert(Product product)
{
HttpPostedFileBase file = product.Image;
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
product.ImageUrl = Path.Combine(Server.MapPath("~/Content/Images/Products/"), fileName);
file.SaveAs(product.ImageUrl);
}
return null;
}
【问题讨论】:
标签: jquery asp.net asp.net-mvc asp.net-mvc-4