gpt4 book ai didi

asp.net-mvc - MVC5 Ajax.BeginForm 上传带有文件的表单

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

我读到一些文章,无法使用 Ajax.BeginForm 保存文件。

我在 MVC5 中有一个使用 Ajax.BeginForm 的表单,因此用户无需刷新页面即可获得良好的响应式应用程序。

现在,要求是添加 4 个用于保存文件的字段(文件上传)。

另请阅读,也许使用 jquery.form.js 这是可能的。

所以我的问题是关于其他方法这是否有意义:

  1. 表单保留Ajax.BeginForm
  2. 用户在表单中输入数据。
  3. 当用户需要将文件加载到表单中时,我正在考虑将该文件上传到服务器并暂时存储在那里。
  4. 保存表单后,我可以在服务器端获取临时文件,然后保存它们。

最佳答案

请检查以下代码以保存单独的表单数据文件上传:

使用 Ajax.BeginForm 查看

@using (Ajax.BeginForm("", "", new AjaxOptions
{
HttpMethod = "POST",
}, new { @id = "UploadFileForm", @class = "form-horizontal" }))
{
<div class="col-sm-3">
<label>Browse</label>
<input type="file" id="file" name="file" />
<p class="help-block">Supported format .doc,.docx,.pdf</p>
</div>
<div class="col-xs-12">
<button type="button" value="Add" id="Addbtn" class="btn btn-primary">
<i class="fa fa-plus-square"></i>&nbsp;Add
</button>
</div>
}

文件上传按钮点击事件:

 $("#Addbtn").click(function () {
// --- code for upload resume
var formdata = new FormData();
var getfile = document.getElementById('file');
for (i = 0; i < getfile.files.length ; i++) {
formdata.append(getfile.files[i].name, getfile.files[i]);
}
function isvalidFileFormat() {
if (getfile.files.length > 0 ) {
var extention = $('#file').val().split('.');
var data;
$.each(extention, function (index, value) {
if (index == 1) {
data = value;
}
});

if (data == "pdf" || data == "docx" || data == "doc") {
return "";
}
else {
return "<p>Please choose .pdf, .docx, .doc file only." + "</p>\n";
}
}
else
return "";
}
}
if (summary) { CustomAlert(summary); return false; } else {
var TestModel = {
"Id": $("#hdnId").val()
};
$.ajax(
{
//Save Main Form Data
url: '/TestController/TestAction/',
type: "Post",
async: false,
dataType: "json",
data: JSON.stringify(TestModel),
contentType: "application/json;charset=utf-8",
success: function (result) {
// After saving main data you can save this file for same user
formdata.append("Userid", result.id);
$.ajax({
url: '/TestController/Fileupload',
data: formdata,
contentType: false,
processData: false,
async: false,
type: 'POST',
success: function (data) {
$("#YourDivName").html(data);
}
});
$("#file").val(null);
}
});
return true;
}
});

这是文件上传的代码

/// <summary>
///File Upload
/// </summary>
/// <param name="Userid"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Fileupload(int Userid = 0)
{
string path = string.Empty;
string filename = string.Empty;
string fileExtention = string.Empty;
string withoutEXT = string.Empty;
string ResumeFilePath = string.Empty;
string ChangeFileName = string.Empty;
bool uploadStatus = false;
if (Request.Files != null && Request.Files.Count > 0)
{

for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
if (file.ContentType == "application/pdf" || file.ContentType == "text/rtf" || file.ContentType == "application/doc"
|| file.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
{
filename = Path.GetFileNameWithoutExtension(file.FileName);
fileExtention = Path.GetExtension(file.FileName);
withoutEXT = fileExtention.Replace(".", "");

ChangeFileName = filename + "_" + locationid + fileExtention;

var ifExistPath = "/Uploads/Files/" + ChangeFileName;
var FileVirtualPath = System.IO.Path.Combine(Server.MapPath("/Uploads/Files/"), ChangeFileName);
path = Path.Combine(Server.MapPath("~/Uploads/Files/"), ChangeFileName);

//delete file

if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
if (ifExistPath != FileVirtualPath)
{
file.SaveAs(path);
uploadStatus = true;
}
else
{
}
}
else
{
ModelState.AddModelError("", "Please upload a PDF or Doc or rtf File");
// return View("", model);
}
if (uploadStatus && path != string.Empty)
{

ResumeFilePath = "/Uploads/Files/";
//Add code for save this file in database here
}
}
}
return PartialView("Test", objMaster);
}

希望这对你有帮助!!

关于asp.net-mvc - MVC5 Ajax.BeginForm 上传带有文件的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644898/

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