(原创)js提交文件,js上传文件,纯js解决无刷新文件上传,不使用form提交文件,并获取返回值(路径url)
2017-04-21 20:12
666 查看
遇到一个棘手的问题,以前一直使用form提交实现文件上传,但是这次需要在不刷新的前提下,把文件上传完,并且返回一个路径给input,以上传到数据库保存起来。单文件多文件都可以。我只上传图片,其他类型可以修改。
不是新技术了,就是用Formdata实现。
期间曾想要用百度Ueditor编辑器的单独上传功能,但是研究了一会,不是那么好用,并且用第三方不可控,也许下个版本就会移除部分函数。经过搜索,终于解决,特贴出代码给大家借鉴:我用的asp.net做后台,后台语言做法基本相同
这是前台html:
不是新技术了,就是用Formdata实现。
期间曾想要用百度Ueditor编辑器的单独上传功能,但是研究了一会,不是那么好用,并且用第三方不可控,也许下个版本就会移除部分函数。经过搜索,终于解决,特贴出代码给大家借鉴:我用的asp.net做后台,后台语言做法基本相同
这是前台html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Ajax提交form</title> <script type="text/javascript"> function uploadqin(fileAttach,imgurl) { var formData = new FormData(); // HTML 文件类型input,由用户选择;fileAttach是input type=file控件的id for (var i = 0; i < fileAttach.files.length; i++) { formData.append(fileAttach.files[i].name, fileAttach.files[i]); } // formData.append("userfile", fileAttach.files[0]);//左边的是单个文件上传,需要去掉input的multiple属性 // JavaScript file-like 对象 var request = new XMLHttpRequest(); request.open("POST", "upload.ashx"); request.send(formData); request.onreadystatechange = () => {//在这里指定上传成功的回调函数,接受返回值 if (request.readyState == 4 && request.status == 200) { let res = request.responseText; // console.log(res) imgurl.value=res; } }; } </script> </head> <body> <input name="imgurl" id="imgurl" type="text" placeholder="请上传图片或输入网络图片地址" style="width:518px;"/> <input type="file" id="uploadimg" value="上传图片" onchange="javascript:uploadqin(document.getElementById('uploadimg'),document.getElementById('imgurl'))" /> </body> </html>后台接收代码:upload.ashx,代码很简单理解,别一看到这么多就害怕,我注释了单文件上传的。
<%@ WebHandler Language="C#" Class="upload" %> using System; using System.Web; using System.IO; using System.Collections; public class upload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp,ico"); //string type_code = context.Request["userName"]; //string xiangmuid = context.Request["userid"]; try { HttpPostedFile file; file = context.Request.Files[0]; string fileName = file.FileName; string fileExt = Path.GetExtension(fileName).ToLower(); if (fileExt == "") { fileExt = ".jpg"; } if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) return; string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt; string year = DateTime.Now.Year.ToString(); string monthday = DateTime.Now.ToString("MMdd"); if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year)) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year); } if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday)) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday); } string lujing = "documentimage/" + year + "/" + monthday + "/" + filename; if (fileExt == ".jpg" || fileExt == ".bmp" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".ico") { shangchuan(file, context.Server.MapPath(lujing)); context.Response.Write("../admin/" + lujing); } } catch (Exception ex) { //context.Response.StatusCode = 500; //context.Response.Write(ex.Message); context.Response.Write("0"); context.Response.End(); } finally { context.Response.End(); } ///下面是多文件上传 /*context.Response.ContentType = "text/plain"; Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp,ico"); //string type_code = context.Request["userName"]; //string xiangmuid = context.Request["userid"]; try { HttpPostedFile file; for (int i = 0; i < context.Request.Files.Count; ++i) { file = context.Request.Files[i]; string fileName = file.FileName; string fileExt = Path.GetExtension(fileName).ToLower(); if (fileExt == "") { fileExt = ".jpg"; } if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) continue; string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt; string year = DateTime.Now.Year.ToString(); string monthday = DateTime.Now.ToString("MMdd"); if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year)) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year); } if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday)) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday); } string lujing = "documentimage/" + year + "/" + monthday + "/" + filename; if (fileExt == ".jpg" || fileExt == ".bmp" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".ico") { shangchuan(file, context.Server.MapPath(lujing)); context.Response.Write("sucess——" + lujing); } //string zhiyoufilename = Path.GetFileName(file.FileName).Replace(fileExt, ""); //string sql_add = "insert into image(image_name,type_code,image_url,xiangmuid) values('" + zhiyoufilename.Trim() + "',"+type_code+",'" + lujing + "'," + xiangmuid + ")"; //string sql_add = "insert into image(type_code,image_url,xiangmuid) values("+type_code+",'" + lujing + "'," + xiangmuid + ")"; } } catch (Exception ex) { //context.Response.StatusCode = 500; //context.Response.Write(ex.Message); context.Response.Write("0"); context.Response.End(); } finally { context.Response.End(); }*/ } public bool IsReusable { get { return false; } } private void shangchuan(HttpPostedFile imgFile, string lujing) { Stream sr = imgFile.InputStream; System.Drawing.Image originalImage = System.Drawing.Image.FromStream(sr); int newwidth = 0; int newheight = 0; caijian(originalImage, 800, 600, ref newwidth, ref newheight); System.Drawing.Image bitmap = new System.Drawing.Bitmap(originalImage, newwidth, newheight); bitmap.Save(lujing, System.Drawing.Imaging.ImageFormat.Jpeg); sr.Close(); bitmap.Dispose(); originalImage.Dispose(); } private void caijian(System.Drawing.Image ASrcImg, int AWidth, int AHeight, ref int nwidth, ref int nheight) { double ADestRate = ASrcImg.Width * 1.0 / ASrcImg.Height; if (ASrcImg.Width >= ASrcImg.Height) { if (ASrcImg.Width >= AWidth) { nwidth = AWidth; nheight = (int)(AWidth / ADestRate); } else { nwidth = ASrcImg.Width; nheight = (int)(ASrcImg.Width / ADestRate); } } else { if (ASrcImg.Height >= AHeight) { 871c nheight = AHeight; nwidth = (int)(AHeight * ADestRate); } else { nheight = ASrcImg.Height; nwidth = (int)(ASrcImg.Height * ADestRate); } } } }
相关文章推荐
- 简单解决 multipart/form-data 文件上传表单中 传递参数无法获取的办法! (解决办法:动态更改表单提交URL)
- 简单解决 multipart/form-data 文件上传表单中 传递参数无法获取的办法! (解决办法:动态更改表单提交URL)
- 【文件上传】使用jquery.form.js来实现表单提交
- 关于使用jquery.form.js上传文件同时提交表单的方法
- 如何使用JS获取IE上传文件路径(IE7,8)
- Play FrameWork 使用jquery.form.js实现无刷新提交带文件的表单
- 使用隐藏的iframe 隐藏form提交,仿AJax无刷新提交,可以实现无刷新上传文件
- js无刷新无插件异步上传文件,使用dojo.io.iframe发送form数据包
- ASP.NET MVC 使用jquery.form.js 异步上传 在IE下返回值被变为下载的解决办法
- 使用隐藏的iframe 隐藏form提交,仿AJax无刷新提交,可以实现无刷新上传文件
- 使用jquery.form.js实现无刷新上传文件
- 关于jquery.form.js插件的无刷新上传文件使用的问题
- js获取文件上传路径(解决出现fakepath的问题)
- (转)使用隐藏的iframe 隐藏form提交,仿AJax无刷新提交,可以实现无刷新上传文件
- 表单包含file上传文件提交,使用ajaxSubmint或者ajaxForm 遇到的问题以及解决方法
- 如何使用JS获取IE上传文件路径(IE7,8)
- httpClient4.3 模拟Post提交,模拟Post上传文件并解决服务端使用spingMVC时upload.parseRequest(request)解析不到File,Pos简单抓取页面数据
- Js获取file上传控件的文件路径总结
- 使用jQuery.form插件实现表单异步提交+上传文件
- 使用ajax提交form表单,包括ajax文件上传