0

我正在使用 MVC 上传一些文件。以下代码工作正常,但我想从服务器返回一些信息(例如消息或 ID)。我想做的很简单,但我担心我没有说清楚。有人可以帮忙吗?

看法

   @using (Html.BeginForm("AddFileX", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
         <input type="file" name="files" multiple="true" />
         <input id="submit" type="submit" value="Upload" />
     }

控制器

   [HttpPost]
    public ActionResult AddFileX(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);
            }
        }
        // I would like to return a message or an ID of something
        // (eg "you are about to overwrite your files" or the ID of something not shown here)
        return View("IdxUpload");  // This line probably needs to be changed
    }
4

2 回答 2

1

查看这篇 Scott Hanselman 文章的底部。他基本上演示了如何将有关文件上传状态的信息发送回用户。特别是,他创建了一个 ViewModel 来保存 fileUpload 结果,根据每个文件的上传状态创建一个结果列表,然后通过将信息传递给要呈现的 View 将信息发送回用户。

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

编辑:

如果您希望在上传时提示用户确认(如果文件已经存在),您可以:

(a) 使用 javascript ajax 调用来检查文件是否存在并在发布之前提示用户 - 或 -

(b) 允许用户提交,将文件保存到临时位置,在另一个视图中提示用户确认,如果用户确认则处理文件。

示例 (a):

[控制器]

public ActionResult AddFileForm() {
   return View();
}

[HttpPost]
public ActionResult AddFileX(IEnumerable<HttpPostedFileBase> files) {
   // do what you need to save your files and/or update your db
   foreach (var file in files) {
      if (file.ContentLength > 0) {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
         file.SaveAs(path);
      }
   }

   // collect the updated file ids and send to View to render (should prob use Strongly typed class(es))
   string[] results = {"123", "456", "789"};

   return View(results);
}

[HttpPost]
public JsonResult FileExists(List<string> filelist) {
   //check if file(s) exist given filename 

   // return ids for files that already exist on your system
   string[] results = {"123", "", "789"};
   return Json(results);
}

[查看] AddFileForm

@using (Html.BeginForm("AddFileX", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   <input id="f1" type="file" name="files" multiple="true" />
   <input id="f2" type="file" name="files" multiple="true" />
   <input id="overwrite" type="hidden" value="false" />
   <input id="submit" type="submit" value="Upload" />
}

<script>
   $(document).ready(function () {
      $('#submit').click(function (e) {
         if ($('#overwrite').val() == 'true')
            return; //proceed w/ submit

         e.preventDefault();

         // collect filenames of proposed file updates
         var files = [];
         $('input[type=file]').each(function () {
            var filename = $(this).val();
            files.push(filename);
         });

         // send request to check if files exist
         $.ajax({
            type: "POST",
            url: "/File/FileExists",
            data: { filelist: files },
            success: function (data) {
               confirmUpload(data);
            },
            traditional: true
         });
      });
   });

   function confirmUpload(results) {
      var existing = false;
      $(results).each(function () {
         var fid = $(this)[0];
         if (fid.length > 0) {
            existing = true; //file exists on Server, fid returned.

            //do stuff..highlight table row..etc
         }
      });

      if (existing) {
         //do whatever to request confirmation, show a message div, etc
         var answer = confirm("Overwrite files?");
         if (answer) {
            // if confirmed, set flag submit form
            $('#overwrite').val('true');
            $('#submit').click();   //$('form').submit() - unreliable
         }
      }
   }
</script>

希望这能给你一些想法。

于 2012-05-09T15:41:48.747 回答
0

如果您不想使用 ajax 文件上传插件,您可以做一件非常简单的事情。

假设您拥有文件上传元素的视图名为 view1,因此当视图 1 发布到操作方法时,请检查文件是否已上传或已经存在(这部分我认为您已经完成)

接下来在 viewbag 中添加一条消息,如下所示 ViewData.Message = "Files has been loaded"; 并返回相同的视图

在您的视图中的任何地方添加一行(最好在最后)。@ViewData.Message。这样,您想向用户显示的任何消息都将显示给用户

于 2013-06-15T17:12:17.967 回答