石鹸's blog

.Net(C#)のWebプログラマ 他サイトの記事紹介やメモ書き

AJAXでファイルアップロード サンプル

アップするファイルサイズに関しては
file.ContentLength
でバイトサイズを見てチェックすればOK




参考サイト様
[C#] HTMLフォームからのファイルのアップロードを受け取る (ファイルアップロードを受け付けるジェネリックハンドラの作成)
http://www.ipentec.com/document/document.aspx?page=csharp-asp-net-create-generic-handler-to-get-form-file&culture=ja-jp

jQueryAjaxでファイルアップロード
http://molaovo.hatenablog.jp/entry/20130111/1357913239

html5の File API を使って、アップロード無しで画像プレビュー
http://d.hatena.ne.jp/favril/20100506/1273143063


HTML側

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">
        $(function () {
            $("#hogeForm").submit(function () {
                var $form, fd;
                $form = $(this);
                fd = new FormData($form[0]);
                $.ajax($form.attr("action"), {
                    type: 'post',
                    processData: false,
                    contentType: false,
                    data: fd,
                    dataType: 'html',
                    success: function (data) {
                        alert(data);
                    }
                });
                return false;
            });
        });

        function preview(ele) {
            if (!ele.files.length) return;  // ファイル未選択

            var file = ele.files[0];
            if (!/^image\/(png|jpeg|gif)$/.test(file.type)) return;  // typeプロパティでMIMEタイプを参照

            var img = document.createElement('img');
            var fr = new FileReader();
            fr.onload = function () {
                img.src = fr.result;  // 読み込んだ画像データをsrcにセット
                document.getElementById('preview_field').appendChild(img);
            }
            fr.readAsDataURL(file);  // 画像読み込み

            // 画像名・MIMEタイプ・ファイルサイズ
            document.getElementById('preview_field').innerHTML =
                'file name: ' + file.name + '<br />' +
                'file type: ' + file.type + '<br />' +
                'file size: ' + file.size + '<br />';
        }
    </script>
</head>
<body>
    <form id="hogeForm" method="post" action="File_Upload.ashx" enctype="multipart/form-data">
        <div><input type="file" name="hogeFile" onchange="preview(this)" /></div>
        <div>コメント:<input type="text" name="hogeText" /></div>
        <div id="preview_field"></div>
        <input id="hogeSubmit" type="submit" value="アップロード" />
    </form>
</body>
</html>


ハンドラ側

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

namespace Ajax_File_Upload
{
    /// <summary>
    /// File_Upload の概要の説明です
    /// </summary>
    public class File_Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            if (context.Request.HttpMethod == "POST")
            {
                //受け取るファイル
                HttpPostedFile file = context.Request.Files["hogeFile"];

                //受け取るファイルの種類をチェック
                if (file.ContentType == "image/jpeg")
                {
                    //
                }
                else
                {
                    context.Response.Write("jpegファイル以外は受け取れません");
                    return;
                }

                //コメント
                string Comment = context.Request.Form["hogeText"];
                //保存場所
                string phyPath = context.Server.MapPath("/UploadFiles/");
                //保存
                file.SaveAs(phyPath + file.FileName);
                //成功時のリターンメッセージ
                context.Response.Write(Comment);

            }
            else
            {
                //POST通信以外は失敗通知
                context.Response.Write("Faile");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}