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 の記事の下部を確認してください。彼は基本的に、ファイルのアップロードのステータスに関する情報をユーザーに送信する方法を示しています。具体的には、fileUpload の結果を保持する ViewModel を作成し、各ファイルのアップロード ステータスに基づいて結果のリストを作成し、その情報を View に渡してレンダリングすることでユーザーに送り返します。

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCInsourcingTestsAndMocks.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 の [View]

@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がアクションメソッドに投稿されたときに、ファイルがアップロードされているか、すでに存在しているかを確認します(この部分は既に行っていると思います)

次に、この ViewData.Message = "Files have been loaded"; のようなメッセージをビューバッグに追加します。同じビューを返します

ビュー内の任意の場所に行を追加します(できれば最後に)。@ViewData.Message. このようにして、ユーザーに表示したいメッセージがユーザーに表示されます

于 2013-06-15T17:12:17.967 に答える