MVC3 + Ajax 图片上传总结 Kevin

方法一:uploadify插件

1.Ajax 往后台Post 的数据有两种,一种是文本类型,一种是大数据文件图片等。而Ajax不能直接传大数据文件,只能借助插件实现该功能。

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

   <script src="http://www.cnblogs.com/Scripts/swfobject.js" type="text/javascript"></script>

    <script src="http://www.cnblogs.com/Scripts/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>

    <link href="http://www.cnblogs.com/Content/uploadify.css" rel="stylesheet" type="text/css" />

    <style type="text/css">
        .textstyle1
        {
            color: Red;
            font-weight: bold;
        }
        .textstyle2
        {
            color: Green;
            font-weight: bold;
        }
    </style>

    <script type="text/javascript">
        $(function () {
            //上传
            $('#fileInput1').uploadify({
                'uploader': '/Content/uploadify.swf',
                'script': '/Upload/AddPic',
                'folder': '/Upload',
                'cancelImg': '/Content/cancel.png',
                'fileExt': '*.xls',
                'fileDesc': '*.xls',
                'sizeLimit': 1024 * 1024 * 4, //4M
                'multi': false,
                'onComplete': fun
            });

        });
        function fun(event, queueID, fileObj, response, data) {
            if (response != "") {
                showInfo("成功上传" + response, true); //showInfo方法设置上传结果     
            }
            else {
                showInfo("文件上传出错!", false);
            }
        }
        //显示提示信息,textstyle2为绿色,即正确信息;textstyl1为红色,即错误信息
        function showInfo(msg, type) {
            var msgClass = type == true ? "textstyle2" : "textstyle1";
            $("#result").removeClass();
            $("#result").addClass(msgClass);
            $("#result").html(msg);
        }
        //如果点击‘导入文件’时选择文件为空,则提示
        function checkImport() {
            if ($.trim($('#fileInput1Queue').html()) == "") {
                alert('请先选择要导入的文件!');
                return false;
            }
            return true;
        } 
    </script>


<div>
    <input type="text" id="test" />
    <p><input id="fileInput1" name="fileInput1" type="file"/></p>
    <p style="margin-top:5px;font-size:14px;font-weight:bold;">
    <a href="javascript:if(checkImport()){$('#fileInput1').uploadifySettings('scriptData',{'name':$('#test').val()});$('#fileInput1').uploadifyUpload();}">导入文件</a></p>
    <p style="margin-top:5px;font-size:14px;font-weight:bold;"><span id="result"></span></p>
</div> 

  后台代码:

namespace qdxy.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AddPic2(HttpPostedFileBase context)
        {
            int s = Request.ContentLength;
            //string fileName = Path.GetFileName(upImg.FileName);
            //string filePhysicalPath = Server.MapPath("~/Upload/"+fileName);


            //string name = "", message = "";
            //byte[] bytes  = new byte[]{};
            //try
            //{
            //    upImg.SaveAs(filePhysicalPath);
            //    name = Path.GetFileName(fileName);

            //    bytes = Encoding.Unicode.GetBytes("图片添加成功");
            //    for (int i = 0; i < bytes.Length; i+=2)
            //    {
            //        message += "\\u" + bytes[i+1].ToString("x").PadLeft(2,'0')+bytes[i].ToString("x").PadRight(2,'0');
            //    }

            //}
            //catch (Exception ex)
            //{
            //    message = ex.Message;
            //}

            return Json(new
            {
                //picpath = "/Upload/" + fileName,
                //message = message
            });
        }

        [HttpPost]
        public JsonResult AddPic(HttpPostedFileBase FileData, string folder, string name)
        {
            string title = string.Empty;
            string message = string.Empty;

            //将传过来的图片映射到物理硬盘的路径上
            string storeFilePath = Server.MapPath("~/Upload/"+FileData.FileName);

            try
            {
                //保存图片的方法
                FileData.SaveAs(storeFilePath);
                title = Path.GetFileName(folder);

                byte[] bytes = Encoding.Unicode.GetBytes("图片上传成功");
                //将图片转换成Unicode编码方便传输
                /*
                 * Unicode和汉字编码小知识 将汉字进行UNICODE编码,
                 * 如:“王”编码后就成了“\u738b”,UNICODE字符以\u开始,后面有4个数字或者字母
                 * ,所有字符都是16进制的数字,每两位表示的256以内的一个数字。
                 * 而一个汉字是由两个字符组成,于是就很容易理解了,
                 * “738b”是两个字符,分别是“73”“8b”。
                 * 但是在将 UNICODE字符编码的内容转换为汉字的时候,
                 * 字符是从后面向前处理的,所以,需要把字符按照顺序“8b”“73”
                 * 进行组合得到汉字
                 * */
                for (int i = 0; i < bytes.Length; i+=2)
                {
                    message += "\\u" + bytes[i + 1].ToString("x").PadLeft(2, '0') + bytes[i].ToString("x").PadRight(2,'0');
                }

            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return Json(new {                    
                title = title,
                message = message
            });
        }

    }
}

  原本是想用Json来返回上传的结果的,但似乎客户端的uploadify插件的方法不支持json格式的数据,有待进一步研究。

方法二:利用 JQueryForm插件 详见:http://www.cnblogs.com/kfx2007/archive/2012/08/27/2658325.html

  这种方法是利用Form提交表单来把大数据传到后台的。

 

 

原文地址:https://www.cnblogs.com/kfx2007/p/2660527.html