ASP.net 利用From实现上传文件

html 表单上传文件

一般处理程序由于没有 apsx 页面的整个模型和控件的创建周期,而比较有效率。这里写一个用 html 表单进行文件上传的示例。

       1. 表单元素选用 <input type="file"> 控件。

       2. form 表单需要设置 enctype="multipart/form-data" 属性,请求报文体中数据格式也由键值对更改为数据头和数具体,并有随机边界符分割。

       3. 服务器端接收文件使用 Request.Files 属性。

       4. 使用 HttpPostedFile 的 SaveAs 方法保存文件(需转换成网站物理路径)。

Html:

1 <form id="upload" enctype="multipart/form-data" method="post">
2   <input name="file1" type="file" id="shangchuaninput" class="hidden file">
3 </form>

JS:

 1   var UserName = $("#yonghuming").val()
 2     var Name = $("#xingming").val()
 3     var UserPwd = $("#mima").val()
 4 
 5     var formData = new FormData($("#upload")[0]);                   //上传的文件
 6 
 7     formData.append('UserName', UserName);         //参数 
 8     formData.append('Name', Name);
 9     formData.append('UserPwd', UserPwd);
10     $.ajax({
11             url: "/Admin/SaveTeacher",
12             async: true,
13             cache: false,
14             type: "POST",
15             processData: false,
16             contentType: false,
17             data: formData,
18             success: function (data) {19             },
20             error: function () {21             }
22         })    

控制器:

       try
            {
                HttpPostedFileBase students = Request.Files[0];
                string csvpath = Server.MapPath("../UploadFolder/LOGO/");
                if (!Directory.Exists(csvpath))
                {
                    Directory.CreateDirectory(csvpath);
                }
                csvpath = csvpath + students.FileName;
                students.SaveAs(Server.MapPath("~/UploadFolder/LOGO/") + Request.Files[0].FileName);
            }
            catch (Exception ex)
            {
            }

webform中:

context.Response.ContentType = "text/plain";
            HttpFileCollection files = context.Request.Files;
            if (files != null && files.Count > 0)
            {
                for (int i = 0; i < context.Request.Files.Count; i++)
                {
                    HttpPostedFile file = context.Request.Files[i];
                    string path = context.Server.MapPath("../../Main/Teacher/Upload/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string csvpath = path + file.FileName;
                    file.SaveAs(csvpath);
                }
                string json = "Teacher/Upload/" + context.Request.Files[0].FileName;
                context.Response.Write(json);
            }
            else
            {
                context.Response.Write("No files");
            }
原文地址:https://www.cnblogs.com/MR---Zhang/p/8135949.html