我想通过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,
});
})
产品getter和setter
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;
}
用这个来代替:
var fileName = file.FileName;
更换你的行
var fileName = Path.GetFileName(file.FileName);
所以如果我要改变你的代码:
var fileName = file.FileName;
product.ImageUrl = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(product.ImageUrl);
如果这不是足够,然后检查这个js我是用我上传的一个代码:
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
这是为我工作的代码:
$(document).on("submit", "#myFormId", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var formData = new FormData(this);
$.ajax({
url: 'my url',
type: 'POST',
data: formData,
success: function (response) {
if (response) {
// Do whatever you want to do with response
}
},
error: function (error) {
console.log(error)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
我看你缺少contentType: false
在阿贾克斯的设置。这是必需的文件上传与阿贾克斯。