(原创)js提交文件,js上传文件,纯js解决无刷新文件上传,不使用form提交文件,并获取返回值(路径url)

来源:互联网 发布:美图秀秀批处理mac版 编辑:程序博客网 时间:2024/05/17 01:56

遇到一个棘手的问题,以前一直使用form提交实现文件上传,但是这次需要在不刷新的前提下,把文件上传完,并且返回一个路径给input,以上传到数据库保存起来。单文件多文件都可以。我只上传图片,其他类型可以修改。

不是新技术了,就是用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)            {                nheight = AHeight;                nwidth = (int)(AHeight * ADestRate);            }            else            {                nheight = ASrcImg.Height;                nwidth = (int)(ASrcImg.Height * ADestRate);            }        }    }}





0 0
原创粉丝点击