记录一下 js + C#使用formdata上传文件

        var filepath = "";
        function getPathFile() {
            //获取文件对象
            var a = document.getElementById("file").files[0];
            var formData = new FormData();
            formData.append("file", a)

            $.ajax({
                type: "post",
                url: "Url",
                data: formData,
                contentType: false,  //需设置为false。因为是FormData对象,且已经声明了属性enctype="multipart/form-data"
                processData: false,  //需设置为false。因为data值是FormData对象,不需要对数据做处理
                async: false, 
                success: function (path) {

                }
            });
        }

C#代码

           foreach (string upload in Request.Files.AllKeys)
           {
                var file = Request.Files[upload];  //file可能为null

                //文件上传
                //HttpPostedFileBase postFileBase = ProductImage;

                //文件后缀
                string extension = Path.GetExtension(file.FileName);

                //文件流
                Stream uploadStream = file.InputStream;

                //把文件写入到本地盘或服务器

                path = "D:\\test\\" + file.FileName;
                using (var fileStream = System.IO.File.Create(path))
                {
                    uploadStream.Seek(0, SeekOrigin.Begin);
                    uploadStream.CopyTo(fileStream);
                }

            }

 

 html代码

<input type= "file" id="file"/>

 

上一篇:FormData用法


下一篇:vue ie报错:[Vue warn]: Error in v-on handler: "ReferenceError: “FormData”未定义"