2018-04-30 (オリジナル) js がファイルを送信し、js がファイルをアップロードし、純粋な js が非更新ファイルのアップロードを解決し、ファイルの送信にフォームを使用せず、戻り値 (パス URL) を取得します。

厄介な問題が発生しました。以前はフォーム送信を使用してファイルをアップロードしていましたが、今回はファイルを更新せずにアップロードし、入力へのパスを返してデータベースにアップロードして保存する必要があります。単一ファイルでも複数ファイルでも問題ありません。写真のみをアップロードします。他のタイプは変更できます。

それはもはや新しいテクノロジーではなく、Formdata によって実現されています。

期間中、Baidu 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="上传图片" οnchange="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);
            }
        }
    }

}





おすすめ

転載: blog.csdn.net/qian913761489/article/details/70338346