gpt4 book ai didi

javascript - 我想将 javascript 中的数据和文件发送到 Controller (但如何)(Mvc asp.net)

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

我有一个这样的脚本,我也想将照片发送到 Controller 但是当我添加发送文件部分时,我无法将文件发送到 Controller 。有没有办法同时发布带有数据的文件?

这是我的代码:

$(document).ready(function () {
$("#btnBecKaydet").click(function () {
var formBeceri = $("#FormumBec").serialize();
$.ajax({
type: "POST",
url: "/Cv/BeceriEkle",
data: formBeceri,
success: function () {
$("#ModelimBec").modal("hide");
}
});
});
});

-----脚本----------

    public ActionResult BeceriEkle(kisiselWeb.Models.tbl_beceri s1 , HttpPostedFileBase file)
{
if(file != null)
{
if (System.IO.File.Exists(Server.MapPath(s1.beceriFoto)))
{
System.IO.File.Delete(Server.MapPath(s1.beceriFoto));
}
WebImage img = new WebImage(file.InputStream);
FileInfo fotoinfo = new FileInfo(file.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(75, 75);
img.Save("~/Foto/Beceri/" + newfoto);
s1.beceriFoto = "/Foto/Beceri/" + newfoto;
}
db.tbl_beceri.Add(s1);
db.SaveChanges();
return RedirectToAction("Cv", "Beceri");
}

-- Controller ---

   <div class="modal-body">
<div class="container">
<form id="FormumBec">
<div class="col-md-12 align-content-center">
@Html.Label("Beceri Başlığı : ", htmlAttributes: new { @class = "control-label col-md-6" })
<input type="text" name="beceriBaslik" /><br />
@Html.Label("Beceri Fotoğrafı : ", htmlAttributes: new { @class = "control-label col-md-12" })
<input type="file" id="BecFot" accept=".jpg,.png,.JPEG,.jpeg" /><br />
</div>
</form>
</div>
</div>

最佳答案

.serialize() 不包含文件类型数据。它只返回可以作为 get 传递的查询字符串。反而使用FormData构造数据这是我的一个存储库中的示例

var formElement = $('#FormumBec');
        var form = document.forms.namedItem(fid);
        var formData = new FormData(form);
        $.ajax({
            //Only file is to be sent via POST
            type: "POST",
            url: "/Cv/BeceriEkle"+ "?" + formElement.serialize(),
            contentType: false,
            processData: false,
            data: formData,
            success: function(data) {
                $("#ModelimBec").modal("hide");
            },
            error: function(err) {
                console.log("Form submit failed with : " + err);
                alert(err);
            }
        });

关于javascript - 我想将 javascript 中的数据和文件发送到 Controller (但如何)(Mvc asp.net),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127763/

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