Skip to main content
 首页 » 编程设计

c#之使用 Ajax 发布的 MVC 中的文件附件

2024年05月22日49pander-it

我在 MVC 应用程序中工作。我的页面中有一个文件上传控件。 我将使用文件上传控件一次只附加文件。我将在带有删除选项的网格中显示文件名。

当我点击保存按钮时需要保存这些文件(但保存按钮通过 Ajax 调用发布数据)。

请给我一个方法。 提前致谢。

请您参考如下方法:

有数以千计的插件可供文件上传使用,您也可以使用基于 HTML5 的解决方案。但是由于您没有指定您使用的是哪个插件,所以我刚刚为您提供了上传和保存文件的完整方法。

<form id="myForm" action="@Url.Action('files', 'controllername')" enctype="multipart/form-data"> 
 
    <input type="file" id="fileUpload" name="fileUpload" /> 
</form> 
 
$("#fileUpload").change(function() { 
    $("#myForm").submit();  // meaning whenever you select the file and press OK/Open, form will be submitted. 
}); 
 
 
public ActionResult files() 
{ 
     if (Request.Files.Count > 0) 
     { 
         var file = Request.Files[0]; 
 
         if (file != null && file.ContentLength > 0) 
         { 
            var fileName = Path.GetFileName(file.FileName); 
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName); 
            file.SaveAs(path); 
         } 
     } 
 
     return RedirectToAction("Index"); 
 } 

如果您在此解决方案中遇到任何问题,请告诉我。