MVC——就酱紫一个系列,这是一个好的开始7

今天做一个图片上传

 

用的是

Ajax Upload

这个Jquery插件 

https://github.com/codler/jQuery-Ajax-Upload

这个支持单文件上传

 

@model Model.Classification
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>添加分类</title>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/Scripts/ajaxupload.3.2.js")
    @*@Scripts.Render("~/Scripts/jquery.ajaxupload.js")*@
    @Scripts.Render("~/Scripts/Image.js")
    <script type="text/javascript">
        $(function () {
            var button = $('#btnUpload'), interval;
            new AjaxUpload(button, {
                action: '/Classification/Upload',
                name: 'coverpicfile',
                data: {
                    controlName: "coverpicfile"
                },
                responseType: 'json',
                onSubmit: function (file, ext) {
                    if (ext && /^(jpg|png|jpeg|bmp|gif)$/.test(ext)) {
                        /* Setting data */
                        button.text('Uploading');
                        this.disable();
                        // Uploding -> Uploading. -> Uploading...
                        interval = window.setInterval(function () {
                            var text = button.text();
                            if (text.length < 13) {
                                button.text(text + '.');
                            } else {
                                button.text('Uploading');
                            }
                        }, 200);
                    } else {
                        // extension is not allowed
                        alert("仅支持*.jpg|.png|.jpeg|.bmp|.gif 图片文件,且文件小于5M!");
                        // cancel upload
                        return false;
                    }
                },
                onComplete: function (file, response) {
                    button.text('上传图片');
                    window.clearInterval(interval);
                    // enable upload button
                    $("#imgbanner").attr("src", response.filename);
                    $("#CoverPic").val(response.photoname);
                    this.enable();
                }
            });
        });
    </script>
</head>
<body>

    @*<h2>添加分类</h2>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Classification</legend>

            <div class="editor-label">
                分类名称
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Classify)
                @Html.ValidationMessageFor(model => model.Classify)
            </div>

            <div class="editor-label">
                分类图片
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.CoverPic)
                @Html.ValidationMessageFor(model => model.CoverPic)
            </div>
            <p>
                <input type="submit" value="添加" />
            </p>
        </fieldset>
    }

    <div>
        @Html.ActionLink("返回列表", "List")
    </div>*@


    <div>
        <div>
            <img src="@Url.Content("~/Content/images/def_b_xx.gif")" title="封面图片" id="imgbanner"
                        width="100" height="100" alt="" onload="javascript:DrawImage(this,375,215)" />
            <p>
                <a href="javascript:void(0);" id="btnUpload">上传图片</a>
            </p>
            @Html.HiddenFor(m => m.CoverPic)
        </div>
        <div>
        </div>
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
</body>
</html>

要引用 


@Scripts.Render("~/Scripts/ajaxupload.3.2.js")

还有jquery

@Scripts.Render("~/Scripts/Image.js") 这个是控制返回图片显示大小的一个方法

 

public JsonResult Upload()
        {
            try
            {

                string PhotoPath = DateTime.Now.ToString("yyyyMMddhhmmss");
                //string controlName = Request["coverpicfile"].ToString();
                HttpRequest request = System.Web.HttpContext.Current.Request;
                HttpFileCollection FileCollect = request.Files;
                HttpPostedFile uploadedFile = FileCollect["coverpicfile"];
                string fullfilename = uploadedFile.FileName; //获取客户端上传的文件信息

                //if (uploadedFile != null)
                //    return "{\"type\":0, \"msg\":\"测试消息:文件不需重复上传!\",\"filename\": \"" + fullfilename + "\"}";

                int uploadFileSize = uploadedFile.ContentLength;    //上传文件长度
                int fileSizeMB = uploadFileSize / 1024 / 1024;    //转换成MB
                int MaxUploadFileSize = 3145728;   //系统限制
                if (uploadFileSize > MaxUploadFileSize)
                {
                    JsonResult json = new JsonResult();
                    json.Data = new
                    {
                        type = "0",
                        msg = "文件大小【{0}】,超出系统【{1}MB】的限制,不能上传此文件!",
                        filename = fullfilename
                    };
                    json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    json.ContentType = "text/html";
                    return json;
                }
                string lastname = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1); // 找到最终的文件名
                string ext = System.IO.Path.GetExtension(lastname).ToLower();   //扩展名
                string newFileName = string.Concat(PhotoPath, ext);

                string uploadPath = System.Web.HttpContext.Current.Server.MapPath(@"../Images/Classification") + "\\";
                //string uploadPath = ImageServer.IMAGESERVER_LOCALPATH + datefile + "\\";
                if (uploadedFile != null)
                {
                    if (!System.IO.Directory.Exists(uploadPath))
                    {
                        System.IO.Directory.CreateDirectory(uploadPath);
                    }
                    uploadedFile.SaveAs(uploadPath + newFileName);
                    //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失

                    JsonResult json = new JsonResult();
                    json.Data = new
                    {
                        type = "1",
                        msg = "文件上传成功!",
                        filename = "../Images/Classification/" + newFileName,
                        photoname = newFileName
                    };
                    json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    json.ContentType = "text/html";
                    return json;

                }
                else
                {

                    JsonResult json = new JsonResult();
                    json.Data = new
                    {
                        type = "0",
                        msg = "请选择文件!",
                        filename = ""
                    };
                    json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    json.ContentType = "text/html";
                    return json;
                }
            }
            catch (Exception ex)
            {

                JsonResult json = new JsonResult();
                json.Data = new
                {
                    type = "0",
                    msg = ex.Message.ToString(),
                };
                json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                json.ContentType = "text/html";
                return json;
            }
        }

期间遇到一个

上传文件后返回一个Json格式的数据,提示上传成功,可是老弹出下载框

的问题

json.ContentType = "text/html";

加上这个属性就ok了

posted @ 2013-12-05 00:54  风飞萧雪  阅读(192)  评论(0)    收藏  举报