JS基础 文件上传

JS中的文件需要通过Form表单进行提交

 1 <div>
 2     <form id="form">
 3         //* input 说明
 4         //1、name必须,否则无法上传
 5         //2、accept规定上传的文件类型,用于过滤其他数据
 6         //3、multiple="multiple"设置可选择多个文件
 7 
 8         <input name="uploadFile" type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
 9     </form>
10     <button id="btn">上传</button>
11 </div>

JS提交

 1 $("#btn").on('click', function () {
 2     // 获取表单(Form)数据
 3     var form = document.getElementById('form');
 4     var formData = new FormData(form);
 5 
 6     // 提交表单数据
 7     $.ajax({
 8         url: "UploadExcel", // 提交的地址
 9         type: 'POST',
10         data: formData,
11         mimeType: "multipart/form-data", // 提交的数据类型
12         contentType: false,
13         cache: false,
14         processData: false,
15         success: function (data, textStatus, jqXHR) {
16             // 成功了
17             debugger;
18         },
19         error: function (jqXHR, textStatus, errorThrown) {
20             // 失败了
21             debugger;
22         }
23     });
24 });

C#后台

1 public ActionResult UploadExcel()
2 {
3     HttpPostedFileBase file = null;
4     if (this.Request.Files != null && this.Request.Files.Count != 0)
5     {
6         file = this.Request.Files[0];
7     }
8     return null;
9 }

 

posted @ 2019-02-05 11:03  咖啡漩涡  阅读(191)  评论(0编辑  收藏  举报