ファイルのアップロードを組み込むことはよくある事で。 複数ファイルを一括で上げたいっていう要件もままある話。 uploadifyってゆーライブラリをよく見るので.Net MVCで使ってみた。
まず、ライブラリ。Flash版とHTML5版があるらしい。 HTML5版は有料っぽい。Flash版はMITライセンスの様子。 Flash版を使って実装。
Flash版をDLして、テケトーなとこに配置して、使いたいページで読む。CSSも。jqueryも使う。
<script src="/Scripts/jquery-1.11.1.js"> <script src="/Scripts/lib/uploadify/jquery.uploadify.min.js"> <link href="/Scripts/lib/uploadify/uploadify.css" rel="stylesheet" />
HTML側(View)はこんな感じ。
@using (Html.BeginForm("DoUpload", "HogeControl", null, FormMethod.Post, new { @class = "form-horizontal", @enctype = "multipart/form-data", @id = "filesform" }))
{
<input type="file" name="file_upload" id="file_upload" />
}
そしたらjavascriptはこんな感じ。
$('#file_upload').uploadify({
'fileSizeLimit': '0',
'buttonText': 'ファイル選択',
'swf': "/Scripts/lib/uploadify/uploadify.swf",
'uploader': "/HogeControl/DoUpload/",
'onUploadSuccess': function (file, data, response) {
alert(data + "をアップロードしました。")
}
});
最後にコントローラ側はこんな感じ。
[HttpPost]
public ActionResult DoUpload(int id, FormCollection collections)
{
var uploadedFile = Request.Files["Filedata"];
if (uploadedFile != null && uploadedFile.ContentLength > 0)
{
var filePath = Path.Combine(Server.MapPath("~/uploads/uploadyfitmp"), string.Format("{1}_{0}{2}", Path.GetFileNameWithoutExtension(uploadedFile.FileName), DateTime.Now.Ticks, Path.GetExtension(uploadedFile.FileName)));
uploadedFile.SaveAs(filePath);
return Content(Path.GetFileNameWithoutExtension(uploadedFile.FileName));
}
return Content("Error!!!");
}