zoukankan      html  css  js  c++  java
  • .net mvc 上传头像

    我用的是mvc5  开发环境vs2017 【仅供参考】

    【视图代码】

    <div >
            <img src="@path" alt="@att.Count" id="pic" style="80px;height:80px;border-radius:50%;" />
            <input id="upload" name="file" accept="image/*" type="file" style="display: none">    
    </div>

    【Ajax代码】

    <script>
        $(function () {
            $("#pic").click(function () {
                $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
                $("#upload").on("change", function () {
                    var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
                    if (objUrl) {
                        $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片
                        upimg();
                    }
                });
            });
        });
    
        //建立一?可存取到?file的url
        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) { // basic
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }
        //上传头像到服务器
        function upimg() {
            var pic = $('#upload')[0].files[0];
            var file = new FormData();
            file.append('image', pic);
            $.ajax({
                url: "/Staff/Upload?ID=@entityId",
                type: "post",
                data: {file: file },
                cache: true,
                contentType: false,
                processData: false,
                success: function (data) {
                    console.log(data);
                    console.log("ok")
                    var res = data;
                    $("#resimg").append("<img src='/" + res + "'>")
                }
            });
        }
    </script>

    【控制器代码】

     /// <summary>
            /// 上传文件
            /// </summary>
            /// <param name="ID">实体对象id</param>
            /// <param name="fileBase">文件对象</param>
            /// <returns></returns>
            [HttpPost]
            public ActionResult Upload(Int32 ID)
            {
                HttpPostedFileBase file = Request.Files[0];
            }
  • 相关阅读:
    ASP.NET的最新安全漏洞Important: ASP.NET Security Vulnerability
    Sql常用日期格式
    倒计时 服务器时间 .NET js javascript
    “备份集中的数据库备份与现有的数据库不同”解决方法
    2010年最佳jQuery插件
    jQuery1.4与json格式兼容问题
    .NET结束外部进程 C#结束外部进程
    十步优化SQL Server中的数据访问
    SQL游标的使用与语法
    SQL2005、SQL2008如何压缩日志文件(log) 如何清除日志
  • 原文地址:https://www.cnblogs.com/shichina/p/10701666.html
Copyright © 2011-2022 走看看