1. 使用 html 的 input 标签
<input type="file" multiple="multiple" id="file_load" />
2. 使用 JS 为 input 的 file 添加一个 change 事件
- $('#file_load').change(function () {
- var fileObj = document.getElementById("file_load").files; // JS 获取文件对象
- if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
- alert("请选择文件");
- return;
- }
- if (fileObj.length> 10) { // 因本人项目需求, 一次最多上传的文件个数不能超过 10 个
- alert("一次上传文件不能超过 10 个");
- return;
- }
- var formData = new FormData(); //FormData 专门用来给 Ajax 向后台传递文件用的
- formData.append("action", "FileLoad");// 向后台传递值, 是键值对的形式
- for (var i = 1; i <= fileObj.length; i++) {
- formData.append("file", fileObj[i]); // 向 formData 里追加文件
- }
- $.Ajax({
- url: "../Method/FileUpload.ashx",
- type: "post",
- cache: false,
- data: formData,
- dataType: 'json', // 这里采用 JSON 格式向后台传递数据, 如果后台需要返回信息也必须返回 JSON 数据 只有这样 Ajax 的回调函数才能接收到后台传过来的值
- cache: false,// 上传文件无需缓存
- processData: false,// 用于对 data 参数进行序列化处理 这里必须 false
- contentType: false,
- success: function (data) {
- if (data == 'OK') {
- // 上传完成
- };
- }
- }
- });
- });
3. 一般处理程序 (上传)
- public void FileLoad(HttpContext context)
- {
- string path = "";// 文件保存路径
- for (int i = 0; i <context.Request.Files.Count; i++)
- {
- HttpPostedFile file = context.Request.Files[i];
- path = context.Server.MapPath("~/File/" + file.FileName);
- file.SaveAs(path);
- }
- // 返回 JSON 数据
- JavaScriptSerializer JS = new JavaScriptSerializer();
- context.Response.Write(JS.Serialize("OK"));
- }
4. 文件下载前端
我这里不方便使用项目中的代码, 所以就简单写个 Demo
- <a href="../Method/FileDowload.ashx?action=DowFile&filename=1.txt">
- 下载
- </a>
- 直接使用 a 标签访问一般处理程序, 带两个参数 分别为需要请求的方法和需要下载的文件名称 action=DowFile,filename=1.txt
4. 一般处理程序 (下载)
- public void DowFile(HttpContext context)
- {
- string filename = context.Request["filename"].ToString(); // 文件名称就是前端传来的 filename 这个参数
- string path = "~/File/" + filename;
- System.IO.FileInfo file = new System.IO.FileInfo(System.web.HttpContext.Current.Server.MapPath(path));
- context.Response.Clear();
- context.Response.Charset = "UTF-8";
- context.Response.ContentEncoding = System.Text.Encoding.UTF8;
- context.Response.AddHeader("Content-Type", "application/octet-stream");
- // 添加头信息, 为 "文件下载 / 另存为" 对话框指定默认文件名, 设定编码为 UTF8, 防止中文文件名出现乱码
- context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
- // 添加头信息, 指定文件大小, 让浏览器能够显示下载进度
- context.Response.AddHeader("Content-Length", file.Length.ToString());
- //// 指定返回的是一个不能被客户端读取的流, 必须被下载
- context.Response.ContentType = "application/ms-excel";
- // 把文件流发送到客户端
- context.Response.WriteFile(path);
- // 停止页面的执行
- context.Response.End();
- }
- 我这个是在项目的跟目录里创建了一个文件夹 File.<input type="file" multiple="multiple" id="file_load" /> 标签的默认样式改法有很多 百度上有
来源: http://www.bubuko.com/infodetail-3025194.html