すらいむがあらわれた

こまんど >  たたかう  にげる

jQuery File Upload + ASP.NET MVC

ブラウザ上へのDrag & DropでファイルをアップロードできるjQueryプラグインjQuery File Upload」をASP.NET MVCで使ってみています。

jQuery File Upload」本体のソースとデモはこちら。
・ソース
blueimp / jQuery-File-Upload - GitHub
https://github.com/blueimp/jQuery-File-Upload
・デモ
http://aquantum-demo.appspot.com/file-upload

Firefox4、Chrome10、Mac版Safari5ではブラウザ上へDrag & Dropしてファイルをサーバーにアップロードできます。
IEなどHTML5のDrag & Drop機能とFile API機能をサポートしないブラウザ*1では「Add File」というボタンをクリックするとダイアログが開いてファイルをアップできます。これはjavascriptでiframeを生成して処理している様子。ここまで面倒見てくれるのがうれしいですね。

上記のGitHubのサイトからソース一式をダウンロードすると中に「example」というフォルダがあり、これがすぐ使えるサンプルになっています。
ただしサーバー側のソースコードphpなので、自分用にC#ASP.NET MVCのコードを書きました。メモ代わりに載せておきます。*2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace jQueryFileUploadTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult FileUpload()
        {
            if (this.Request.Files.Count == 0)
            {
                return Content("No files received.", "text/plain");
            }
            else
            {
                HttpPostedFileBase uploadedfile = this.Request.Files[0];

                string fileName = Path.GetFileName(uploadedfile.FileName);
                string fileType = uploadedfile.ContentType;
                int fileSize = uploadedfile.ContentLength;

                uploadedfile.SaveAs(this.HttpContext.Server.MapPath("/Upload") + "\\" + fileName);

                JsonResult result = Json(
                    new object[]{
                        new{
                                name = fileName,
                                size = fileSize,
                                url = "//Your Site/Upload/" + fileName,
                                thumbnail_url = "//Yoor Site/Content/img_arrow.png",
                                delete_url = "//Your Site/Home/FileDelete?filename=" + HttpUtility.UrlEncode(fileName),
                                delete_type = "Delete"
                            }
                        }
                    );

                // ifreme対策
                result.ContentType = "text/plain";
                return result;
                
            }
        }

        public ActionResult FileDelete(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                return Json(false);
            }

            bool result = false;

            FileInfo fi = new FileInfo(this.HttpContext.Server.MapPath("/Upload") + "\\" + HttpUtility.UrlDecode(fileName));
            if (fi.Exists)
            {
                fi.Delete();

                result = true;
            }

            return Json(result);
        }

    }
}

「example」のhtmlの方はformのaction属性のurlを変えるだけで、ほぼそのまま使えます。

VisualStudio 10用のプロジェクト一式はこちら。
https://bitbucket.org/hayashih/jqueryfileuploadtest/downloads


実は最近になって「jQuery File Upload」は根本的に書き換えられたんですよねー。
現在のバージョンと以前のバージョン(v.4)はUIもAPIもOptionもがさっと変わってます。
特にUIは激変。以前のバージョンのUIはこちらにスクリーンショットが載っています。
http://phpspot.org/blog/archives/2011/03/jqueryjquery_fi.html
「Upload File」という緑色の枠にファイルを近づけると枠がびよーん!と伸びてファイルをDropできるというUIでした。これはHTML5 Drag & DropのサンプルコードでよくみかけるUIでいかにもな感じです。
ですが、実はこのUIは実際にサイトに組み込んで使ってみるといまひとつだったりもします。HTML5 Drag & Dropはまだまだ一般的ではありません。多くの人たちは枠の中にファイルをドロップするという動作自体に気がつかないため、とっつきにくいUIなのです。現状はDrag & Drop対応のブラウザでも「Add File」というボタンがあったほうが使いやすいと思います。

なので新バージョン「jQuery File Upload」のUIはより実用的な方に進化してGood Jobだと思います(^^)

■ついでに
ASP.NET WebForm用のサンプルは旧バージョン(v.4)用ですが、以下のページで紹介されています。
https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload-for-C%23-%28Forms%29
サーバー側のコードは現バージョンのjQueryFileUploadでもほとんど変わりなく使えるはずです。たぶんアップロード成功後に戻すJSONを少し書き換えればいいと思う。

*1:IE9もそうです。FileAPIのサポートがありません。

*2:実はサムネイル生成をさぼってます。。。私には要らなかった。