web 表单方式上传文件方法(不用flash插件)
原理:使用表单的input type="file"标签,通过ajax提交表单请求,后台获取请求中的文件信息,进行文件保存操作
由于我测试用的做了一个上传文件和上传图片方法,所以我有两个请求方法
1、html页面
1)图片上传页面
@{ ViewBag.Title = "Images"; } <!doctype html> <html> <head> <meta charset="utf-8"> <title>上传文件测试</title> </head> <script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script> <script type="text/javascript" src="~/Scripts/com.Upload.js"></script> <script> var uploadClick = function () { //1、调用上传附件方法 var dts = coms.doUploadImage(); //将返回格式解析成json对象 var result = JSON.parse(dts); //2、调用保存附件信息方法 //3、输出提示信息 if (result.Success) { //获取文件相关信息(文件名、文件大小、文件路径等) var array = result.Data; //根据返回文件信息和页面数据,组成ajax请求,保存文件信息到数据库中 alert("图片上传成功"+ array.length +"个"); } else { alert("图片上传失败!"); } } </script> <style type="text/css"> .clear { clear: both; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; } </style> <body> <div id="master"> <form id="uploadForm"> <div style="margin: 20px 0px -20px 20px;width:250px;"> <div style="width:30%;margin-top:15px;">图片上传:</div> <div style="width:60%;margin-top:15px;"> <input id="doc" type="file" name="Picture" multiple="multiple" onchange="javascript:coms.setImagePreviews()" accept="image/*" /> </div> </div> <div class="clear"></div> <!-- 存放预览图片的区域 --> <div id="dd" style="margin-left: 5%;width:auto;margin-top:50px;"></div> <div class="clear"></div> <div style="position: absolute;width: 100%;margin-top: 10px;font-weight: bolder;"> <a href="javascript:uploadClick()" >上传</a> </div> </form> </div> </body> </html>
2)上传文件页面
<!doctype html> <html> <head> <meta charset="utf-8"> <title>上传文件测试</title> </head> <script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script> <script type="text/javascript" src="~/Scripts/com.Upload.js"></script> <script> var uploadClick = function () { //1、调用上传附件方法 var dts = coms.doUploadFile(); //将返回格式解析成json对象 var result = JSON.parse(dts); //2、调用保存附件信息方法 //3、输出提示信息 if (result.Success) { //获取文件相关信息(文件名、文件大小、文件路径等) var array = result.Data; //根据返回文件信息和页面数据,组成ajax请求,保存文件信息到数据库中 alert("文件上传成功"+ array.length +"个"); } else { alert("文件上传失败!"); } } </script> <style type="text/css"> .clear { clear: both; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; } </style> <body> <div id="master"> <form id="uploadForm"> <div style="margin: 20px 0px -20px 20px;width:250px;"> <div style="width:30%;margin-top:15px;">文件上传:</div> <div style="width:60%;margin-top:15px;"> <input id="doc" type="file" name="files" multiple="multiple" /> </div> </div> <div class="clear"></div> <div style="position: absolute;width: 100%;margin-top: 25px;font-weight: bolder;"> <a href="javascript:uploadClick()">上传</a> </div> </form> </div> </body> </html>
2、com.Upload.js文件内容(自定义)
var coms = {}; //执行图片上传方法(保存) coms.doUploadImage = function () { var result; var formData = new FormData($("#uploadForm")[0]); console.log(formData); if (formData == null || formData == undefined) { alert("未找到上传图片信息"); return; } $.ajax({ type: "POST", url: '/FileUpload/MultiUploadImage', data: formData, async: false, contentType: false, processData: false, success: function (dts) { result = dts; }, error: function (res) { alert(res.responseText); } }); return result; } //执行上传附件方法(保存) coms.doUploadFile = function () { var result; var formData = new FormData($("#uploadForm")[0]); console.log(formData); if (formData == null || formData == undefined) { alert("未找到上传文件信息"); return; } $.ajax({ type: "POST", url: '/FileUpload/MultiUploadFile', data: formData, async: false, contentType: false, processData: false, success: function (dts) { result = dts; }, error: function (res) { alert(res.responseText); } }); return result; } //多图片上传预览方法 coms.setImagePreviews = function (avalue) { //获取选择图片的对象 var docObj = document.getElementById("doc"); //后期显示图片区域的对象 var dd = document.getElementById("dd"); dd.innerHTML = ""; //得到所有的图片文件 var fileList = docObj.files; //循环遍历 for (var i = 0; i < fileList.length; i++) { //动态添加html元素 dd.innerHTML += "<div style='float:left' > <img id='img" + i + "' /> </div>"; //获取图片imgi的对象 var imgObjPreview = document.getElementById("img" + i); if (docObj.files && docObj.files[i]) { //火狐下,直接设img属性 imgObjPreview.style.display = 'block'; imgObjPreview.style.width = '100px'; imgObjPreview.style.height = '90px'; //imgObjPreview.src = docObj.files[0].getAsDataURL(); //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式 imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]); //获取上传图片文件的物理路径 } else { //IE下,使用滤镜 docObj.select(); var imgSrc = document.selection.createRange().text; //alert(imgSrc) var localImagId = document.getElementById("img" + i); //必须设置初始大小 localImagId.style.width = "100px"; localImagId.style.height = "90px"; //图片异常的捕捉,防止用户修改后缀来伪造图片 try { localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"; localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc; } catch (e) { alert("您上传的图片格式不正确,请重新选择!"); return false; } imgObjPreview.style.display = 'none'; document.selection.empty(); } } return true; }
3、控制器页面
public class HomeController : Controller { /// <summary> /// 访问上传图片页面 /// </summary> /// <returns></returns> public ActionResult Images() { return View(); } /// <summary> /// 访问上传文件页面 /// </summary> /// <returns></returns> public ActionResult Files() { return View(); } }
4、服务器上传方法
1)FileUploadController 内容:
public class FileUploadController : Controller { #region 多文件上传保存 FileUploadService myService = new FileUploadService(); /// <summary> /// 上传多个图片 /// </summary> [HttpPost] public string MultiUploadImage() { JsonReturn result = new JsonReturn(); bool flag = false; string msg = string.Empty; string itemMsg = string.Empty; JArray array = new JArray(); int count = 0; try { //获取所有客户端的表单数据的文件 var files = System.Web.HttpContext.Current.Request.Files; if (files.Count > 0) { //循环所有文件信息 for (var i = 0; i < files.Count; i++) { var file = files[i]; //物理上保存文件信息 JObject myFiles = myService.UploadImage(file, ref itemMsg); //如果是空对象时,证明未保存成功 if (myFiles == null) { //返回失败状态 flag = false; msg = itemMsg; break; } else { //追加到数组中 array.Add(myFiles); count++; //返回成功状态 flag = true; msg = "上传成功"; } } } //返回成功或失败信息 result.Success = flag; result.Message = msg; result.Count = count; result.Data = array; } catch (Exception ex) { flag = false; msg = ex.Message; //返回失败结果信息 result.Success = flag; result.Message = msg; result.Count = count; } //记得序列化出去 return JsonConvert.SerializeObject(result); } /// <summary> /// 上传多个文件 /// </summary> [HttpPost] public string MultiUploadFile(string id) { JsonReturn result = new JsonReturn(); bool flag = false; string msg = string.Empty; string itemMsg = string.Empty; JArray array = new JArray(); int count = 0; try { //获取所有客户端的表单数据的文件 var files = System.Web.HttpContext.Current.Request.Files; if (files.Count > 0) { //循环所有文件信息 for (var i = 0; i < files.Count; i++) { var file = files[i]; //物理上保存文件信息 JObject myFiles = myService.UploadFile(file, ref itemMsg); //如果是空对象时,证明未保存成功 if (myFiles == null) { //返回失败状态 flag = false; msg = itemMsg; break; } else { //追加到数组中 array.Add(myFiles); count++; //返回成功状态 flag = true; msg = "上传成功"; } } } //返回成功或失败信息 result.Success = flag; result.Message = msg; result.Count = count; result.Data = array; } catch (Exception ex) { flag = false; msg = ex.Message; //返回失败结果信息 result.Success = flag; result.Message = msg; result.Count = count; } //记得序列化出去 return JsonConvert.SerializeObject(result); } /// <summary> /// 定义返回格式 /// </summary> public class JsonReturn { public JsonReturn() { } public JsonReturn(bool bo, string msg) { _Success = bo; Message = msg; } public JsonReturn(bool bo, string msg, int count) { _Success = bo; Message = msg; Count = count; } private bool _Success = false; /// <summary> /// 调用是否成功 /// </summary> public bool Success { get { return _Success; } set { _Success = value; } } /// <summary> /// 返回的信息 /// </summary> public string Message { get; set; } /// <summary> /// 返回数量 /// </summary> public int Count { get; set; } /// <summary> /// 返回数据 /// </summary> public object Data { get; set; } } #endregion }
2、FileUploadService的内容
public class FileUploadService { #region 文件上传的方法 /// <summary> /// 上传单个图片 /// </summary> public dynamic UploadImage(HttpPostedFile file, ref string msg) { JObject obj = new JObject(); try { string newFileName = string.Empty; string newFilePath = string.Empty; string newFileSize = string.Empty; //1、检查上传的文件路径是否存在 //获取当前程序集的文件路径 string applicationPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); //获取程序集路径+文件夹路径 string toServerPath = applicationPath + "\\" + ConfigurationManager.AppSettings["UploadImage"]; //拼接上年月文件夹( C:\\UploadFiles\\201904 ) toServerPath = toServerPath + "\\" + DateTime.Now.ToString("yyyyMM"); //判断服务器文件夹路径是否存在 if (!Directory.Exists(toServerPath)) { //不存在路径,则创建 Directory.CreateDirectory(toServerPath); } //2、检查文件的格式 //指定上传文件格式类型 string[] fileExts = { ".jpg", ".jpeg", ".gif", ".png", ".bmp", ".ico" }; //获取上传文件的后缀名 string fileExt = Path.GetExtension(file.FileName).ToLower(); //只上传包含的文件类型 if (fileExts.Contains(fileExt)) { //获取新文件名(包含后缀名) newFileName = Guid.NewGuid().ToString() + fileExt; //file.FileName; //拼接最终的保存文件路径(C:\UploadFiles\201904\01.jpg) newFilePath = toServerPath + "\\" + newFileName; //检查保存是否已存在,存在不做保存 if (!System.IO.File.Exists(newFilePath)) { //3、保存上传的文件 file.SaveAs(newFilePath); } //计算文件的大小(转成字符) newFileSize = GetFileSize(newFilePath); // file.ContentLength; 获取文件的字节 //获取相对路径 string relatePath = newFilePath.Substring(applicationPath.Length, newFilePath.Length - applicationPath.Length); //返回文件相关信息 obj.Add("Old_FileName", file.FileName); obj.Add("FileName", newFileName); obj.Add("FilePath", newFilePath); //文件全路径 obj.Add("FileDirect", relatePath); //相对路径 obj.Add("FileSize", newFileSize); obj.Add("FileExt", fileExt); } else { msg = "上传失败,请选择扩展名为:JPG,JPEG,GIF,PNG,BMP等类型图片!"; obj = null; } } catch (Exception ex) { msg = ex.Message; obj = null; } return obj; } /// <summary> /// 上传单个文件 /// </summary> public dynamic UploadFile(HttpPostedFile file, ref string msg) { JObject obj = new JObject(); try { string newFileName = string.Empty; string newFilePath = string.Empty; string newFileSize = string.Empty; //1、检查上传的文件路径是否存在 //获取当前程序集的文件路径 string applicationPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); //获取程序集路径+文件夹路径 string toServerPath = applicationPath + "\\" + ConfigurationManager.AppSettings["UploadFile"]; //拼接年月文件夹 toServerPath = toServerPath + "\\" + DateTime.Now.ToString("yyyyMM"); //判断服务器文件夹路径是否存在 if (!Directory.Exists(toServerPath)) { //不存在路径,则创建 Directory.CreateDirectory(toServerPath); } //2、检查文件大小是否超过 int filebyte = file.ContentLength; //单位kb(字节) string conSize = ConfigurationManager.AppSettings["UploadFileSize"]; int conbyte = Convert.ToInt32(conSize) * 1000 * 1000; if (filebyte > conbyte) { msg = string.Format("上传失败,上传文件超过最大限制{0}MB!", conSize); obj = null; } else { //3、保存上传的文件 //上传文件筛选掉图片格式 string[] fileExts = { ".jpg", ".jpeg", ".gif", ".png", ".bmp", ".ico" }; //获取上传文件的后缀名 string fileExt = Path.GetExtension(file.FileName).ToLower(); if (fileExts.Contains(fileExt)) { msg = "上传失败,上传附件不包含图片格式!"; obj = null; } else { //获取新文件名(包含后缀名) newFileName = Guid.NewGuid().ToString() + fileExt; //file.FileName; //拼接最终的保存文件路径(C:\UploadFiles\201904\01.jpg) newFilePath = toServerPath + "\\" + newFileName; //检查保存是否已存在,存在不做保存 if (!System.IO.File.Exists(newFilePath)) { //3、保存上传的文件 file.SaveAs(newFilePath); } //计算文件的大小(转成字符) newFileSize = GetFileSize(newFilePath); //获取相对路径 string relatePath = newFilePath.Substring(applicationPath.Length, newFilePath.Length - applicationPath.Length); //4、返回文件相关信息 obj.Add("Old_FileName", file.FileName); obj.Add("FileName", newFileName); obj.Add("FilePath", newFilePath); //文件全路径 obj.Add("FileDirect", relatePath); //相对路径 obj.Add("FileSize", newFileSize); obj.Add("FileExt", fileExt); } } } catch (Exception ex) { msg = ex.Message; obj = null; } return obj; } /// <summary> /// 获取文件的大小 /// </summary> /// <param name="sFileFullName"></param> /// <returns></returns> public string GetFileSize(string sFileFullName) { FileInfo fiInput = new FileInfo(sFileFullName); double len = fiInput.Length; string[] sizes = { "B", "KB", "MB", "GB" }; int order = 0; while (len >= 1024 && order + 1 < sizes.Length) { order++; len = len / 1024; } string filesize = String.Format("{0:0.##} {1}", len, sizes[order]); return filesize; } #endregion }
5、webconfig配置
1)在<appSettings>下添加如下配置
<!--保存上传图片文件夹 --> <add key="UploadImage" value="UploadImages"/> <!--保存上传附件文件夹 --> <add key="UploadFile" value="UploadFiles"/> <!--保存上传附件最大大小,单位MB--> <add key="UploadFileSize" value="4"/>
配置文件和图片保存的文件夹名称,及上传文件时的最大上传
2)在<system.web>下添加如下配置
<!--最大请求长度,单位为KB(千字节),默认为4M,设置为1G,上限为2G --> <httpRuntime maxRequestLength="1048576" executionTimeout="3600" targetFramework="4.5" />
3)在<system.webServer>下添加如下配置
<!--允许上传文件长度,单位字节(B),默认为30M,设置为1G,最大为2G --> <security> <requestFiltering> <requestLimits maxAllowedContentLength="1073741824"/> </requestFiltering> </security>
解决程序默认上传最大4M的配置
6、上传效果图
1)存放文件路径(运行项目下的文件)
2)图片预览效果
3)上传图片效果
7、web上传文件Demo下载
链接:https://pan.baidu.com/s/1QKpleoVdJ6sAhLIeNJSUZg
提取码:avcc
平时多记记,到用时才能看看,记录你的进步,分享你的成果