隐藏

jQuery + Ajax + WebAPI 上传文件

发布:2022/5/25 23:06:17作者:管理员 来源:本站 浏览次数:1042

<div>
        <input name="Userfile" id="Userfile" type="file">
        <input type="button" id="uploadfile" />
    </div>
    <div>
        <p>
            <input type="file" id="upfile"></p>
        <p>
            <input type="button" id="upJS" value="用原生JS上传"></p>
        <p>
            <input type="button" id="upJQuery" value="用jQuery上传"></p>
    </div>


<script>
        // 原生JS版
        document.getElementById("upJS").onclick = function () {
            /* FormData 是表单数据类 */
            var fd = new FormData();
            var ajax = new XMLHttpRequest();
            fd.append("upload", 1);
            /* 把文件添加到表单里 */
            fd.append("upfile", document.getElementById("upfile").files[0]);
            ajax.open("post", "http://localhost:6890/upload/UploadPostImgs", true);

            ajax.onload = function () {
                console.log(ajax.responseText);
            };

            ajax.send(fd);
        }
        // jQuery版
        $('#upJQuery').on('click', function () {
            var fd = new FormData();
            fd.append("upload", 1);
            fd.append("upfile", $("#upfile").get(0).files[0]);
            $.ajax({
                url: "http://localhost:6890/upload/UploadPostImgs",
                type: "POST",
                processData: false,
                contentType: false,
                data: fd,
                success: function (d) {
                    console.log(d);
                }
            });
        });

    </script>
    <script>
        $(function () {
            $("#uploadfile").click(function () {
                var formDate = new FormData();
                var files = $("#Userfile").get(0).files;

                formDate.append("Userfile", files[0]);
                //如果有其他参需要一起提交到后台
                formDate.append("location", location);

                $.ajax({
                    type: "POST",
                    url: "http://localhost:6890/upload/imgs",
                    contentType: false,
                    cache: false,
                    processData: false,
                    data: formDate,
                    error: function (request) {
                        console.log(request);
                    },
                    success: function (data) {
                        console.log(data);
                    }
                });
            });
        });

    </script>


private string uploadPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Upload/";
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns>成功返回图片URL,失败则返回错误信息</returns>
        [HttpPost, Route("UploadPostImgs")]
        public string UploadPostImgs()
        {
            string result = string.Empty;
            string imgPath = string.Empty;

            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection fileCollection = request.Files; // 判断是否有文件
            if (fileCollection.Count > 0)
            {
                // 获取图片文件
                HttpPostedFile httpPostedFile = fileCollection[0];
                // 文件扩展名
                string fileExtension = Path.GetExtension(httpPostedFile.FileName);
                // 图片名称
                string fileName = Guid.NewGuid().ToString() + fileExtension;
                // 图片上传路径
                string filePath = uploadPath + fileName;
                // 验证图片格式
                if (fileExtension.Contains(".jpg")
                    || fileExtension.Contains(".png")
                    || fileExtension.Contains(".bmp"))
                {
                    // 如果目录不存在则要先创建
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    // 保存新的图片文件
                    while (File.Exists(filePath))
                    {
                        fileName = Guid.NewGuid().ToString() + fileExtension;
                        filePath = uploadPath + fileName;
                    }
                    httpPostedFile.SaveAs(filePath);
                    // 把文件的存储路径保存起来

                    // 返回图片URL
                    imgPath = fileName;
                    result = imgPath;
                }
                else
                {
                    result = "请选择jpg/png/bmp格式的图片";
                }
            }
            else
            {
                result = "请先选择图片!";
            }
            return result;

        }