gpt4 book ai didi

javascript - 为什么我的ajax不发送在 Controller 端上传的图像?

转载 作者:行者123 更新时间:2023-12-03 06:21:12 25 4
gpt4 key购买 nike

我正在使用 jquery ajax 将模型和图像一起发送到我的 Controller 。这是我的表格。

  @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "CreateUser" ,enctype = "multipart/form-data" } ))
{

@Html.AntiForgeryToken();
@Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="col-xs-6">
@*----FIRST NAME----*@
<label>
First Name <span class="text-red font12">*</span>
</label>
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", id = "txtFirstName", @maxlength = "30" })
</div>


<div class="col-xs-6">
@*----LAST NAME----*@
<label>
Last Name <span class="text-red font12">*</span>
</label>

@Html.TextBoxFor(model => model.LastName, new { @class = "form-control", id = "txtLastName", @maxlength = "30" })
</div>

<div class="col-xs-6">
@*----Logo Upload----*@

<label>
Logo Uploaad <span class="text-red font12">*</span>
</label>
<div class="input-group">


<input type="file" id="FileUpload1" />

</div>

</div>
</div>

<div class="row">
<div class="col-xs-4" style="float:right;">
<input type="button" value="Save" class="btn btn-primary btn-block btn-flat" onclick="validateandcreate();" />
</div>
</div>

}这是我的 jquery 代码

function CreateUser() {

var username = $("#txtUserName").val();

var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;

var fileData = new FormData();

// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}


debugger;
if (username != "") {

var model = {
"FirstName": encodeURIComponent($("#txtFirstName").val()),
"LastName": encodeURIComponent($("#txtLastName").val())
};


$.ajax({
url: '/User/Create',
method: 'post',
dataType: 'json',
data: { m: model, f: fileData },
success: function (data) {
alert("success");
},
error: function (err) {

alert("error");
}
});
}
}

如果我仅发送模型,则它工作正常,但如果我随其发送上传的图像,则不会击中 Controller 。这是我的 Controller 。

   [HttpPost]
//[AuthorizationFilter]
[ValidateAntiForgeryToken]
public JsonResult Create(Models.Users user, HttpPostedFileBase file_Uploader)
{
//code
}

最佳答案

您需要在ajax上设置processData: falsecontentType: false才能通过jQuery.ajax()提交文件

您还可以将文件以外的数据添加到 FormData 中。

var formdata = new FormData();
formdata.append("file", fileobject);
formdata.append("model", JSON.stringify({
name: "Johny",
lastname: "Good"
}));

$.ajax({
url: '/User/Create',
method: 'post',
dataType: 'json',
contentType: false,
processData: false,
data: formdata,
success: function(data) {
alert("success");
},
error: function(err) {

alert("error");
}
});

参见Ajax File Uploads

关于javascript - 为什么我的ajax不发送在 Controller 端上传的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38865622/

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