gpt4 book ai didi

jquery - 如何使用ajax和其他附加字段上传文件?

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

我是 ajax 和 .net MVC 新手。

我的应用程序中有 mvc 表单助手的形式,并尝试使用其他表单字段上传文件。

@using (Html.BeginForm("upload", "upload", FormMethod.Post, new { enctype = "mutipart/form-data" })) {

<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.cardTitle)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.cardTitle, new { @Class = "span12", type = "text" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.cardHashCode)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.cardHashCode, new { id = "cardhashcode" })
</div>
<input type="file" name="file" id="file_upload" />
<input type="submit" class="btn btn-success" value="Create One" />
</fieldset>
}

Controller -

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, CardModel card, FormCollection forms) {
CardTable cardtable = new CardTable();
if (file != null && file.ContentLength > 0) {
// TODO: storing uploaded files to the App_Data folder on the server.
// Adjust this location to fit your requirements
var filepath = "D:\\FunRanger2\\FunRangerPhotos";
var filename = Path.Combine(filepath, Path.GetFileName(file.FileName));
file.SaveAs(filename);
cardtable.CardFileName = file.FileName;
cardtable.CardFilePath = filepath;
cardtable.CardDate = DateTime.Now;
cardtable.CardTitle = card.cardTitle;
cardtable.CardHashCode = card.cardHashCode == null ? "" : card.cardHashCode;
db.CardTables.InsertOnSubmit(cardtable);
db.SubmitChanges();

}
}

我仅在输入字段模型中获取值,并且文件始终为空。

我也尝试通过脚本映射它 -

通过给表单一个id来表单#form-upload和按钮button-upload

<script type="text/javascript">
$(function(){
$('#button-upload').click(function(){
$.ajax({
url:'/Upload/Upload/',
data:$('#form-upload').serialize()+$('#file_upload').file,
success:function(){
alert("Uploaded successfully");
}
});
});
});
</script>

如何使用其他表单字段上传文件?请帮助我!

最佳答案

这样使用是我从不同网站搜索得到的。

// Get form 
var form = $('#fromEdit')[0]; // Important!
// Create an FormData object
var data = new FormData(form); // Important!

alert(form);
alert(data);

$.ajax({
type: "POST",
enctype: 'multipart/form-data', // Important!
url: $(this).attr('action'), // Important!
data: data,
processData: false, // Important!
contentType: false, // Important!
cache: false,
success: function(res) {
alert("Records added Successfully.");

}
});

public ActionResult Create([Bind(Exclude = "FileContent")] ProductEntity productEntity) {

foreach(string file in Request.Files) {
HttpPostedFileBase postedFile = Request.Files[file];
}

}

关于jquery - 如何使用ajax和其他附加字段上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21317918/

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