jq 图片文件上传,并预览和展示缩略图,请求给ashx处理上传到服务器

以下仅是给自己做个记录,当然也有参考各位大佬的,方便以后查阅
html部分

  <form id="uploadForm" enctype="multipart/form-data">
                    <input type="file" id="uploadImg" onchange="UploadImg(this)"> 
                    <canvas id="canvasImg"></canvas> 
                     <span>付款凭证:</span>--%>
                    <div style="position: absolute; top: 20px; right: 20px;">
                          <a onclick="showCanvasImg()" href="javascript:void(0);">预览</a>&nbsp;&nbsp;
                        <a onclick="ajaxFileUpload()" href="javascript:void(0);">上传</a>
   </form>

jq部分

  function  UploadImg(obj) {
            file = obj.files[0];
            //var url = window.webkitURL.readAsDataURL(file);
            //alert(url);

            if (file != null) {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                //将file对象base64转码成功后进入
                reader.onload = function () {
                    //声明img标签,并将未压缩的图片赋值给src属性
                    var image = $('#selectImg');
                    image.attr('src', this.result);
                    image.on('load', function () {
                        //定义canvas的宽、高为72px
                        var square = 72;
                        var canvas = $('#canvasImg');
                        var context = document.getElementById("canvasImg").getContext("2d");
                        // Canvas.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); 
                        canvas.width = square;
                        canvas.height = square;
                        context.clearRect(0, 0, canvas.width, canvas.height);
                        var imageWidth;
                        var imageHeight;
                        var imageHeight;
                        var offsetX = 0;
                        var offsetY = 0;
                        //判断是根据原图片的宽压缩还是高压缩
                        if (canvas.width > canvas.height) {
                            imageWidth = Math.round(square * canvas.width / canvas.height);
                            imageHeight = square;
                            offsetX = - Math.round((imageWidth - square) / 2);
                        } else {
                            imageHeight = Math.round(square * canvas.height / canvas.width);
                            imageWidth = square;
                            offsetY = - Math.round((imageHeight - square) / 2);
                        }
                        context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                        //data即为压缩为72x72的压缩图片的base64内容
                        var data = canvas.toDataURL('image/jpeg');
                    });
                };
              
            }
        }

与后台交互的jq代码:

     function ajaxFileUpload() {

            var fileObj = document.getElementById("uploadImg").files[0]; // js 获取文件对象
            if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                alert("请选择图片");
                return;
            }
            var formFile = new FormData();//post文件到后台,必须是from,而且要申明enctype="multipart/form-data"
            formFile.append("action", "UploadVMKImagePath");
            formFile.append("file", fileObj); //加入文件对象

            $.ajax({
                url: "../kalianfu/UploadImgSave.ashx",
                type: 'post',
                data: formFile,
                processData: false,
                cache: false, 
                processData: false,
                contentType: false,
                success: function (data) {
                    //data = "{msg:"timg (3)201908211037558032.jpg",code:"10000"}" 需要转换为json对象
                    console.log(JSON.parse(data), '--');
                    const DATA = JSON.parse(data);
                    payCertificate = getRootPath() + "/uploadfile/" + DATA.msg;
                    console.log(payCertificate, '-----payCertificate----')
                    $("#payCertificate").val(payCertificate);
                    if (DATA.code = "10000") {
                        alert("上传成功!");
                    } else {
                        alert(DATA.msg)
                    }
                }, error: function () {
                    alert("上传失败!");
                }
            })
        }
        function getRootPath() {
            //获得根目录  http://kalianfu.mobile-lapramol.co/m~/uploadfile/tim
            var strFullPath = window.document.location.href;
            var strPath = window.document.location.pathname;
            var pos = strFullPath.indexOf(strPath);
            var prePath = strFullPath.substring(0, pos); 
            return (prePath);
        }

ashx部分

<%@ WebHandler Language="C#" Class="UploadImgSave" %>

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Web;

public class UploadImgSave : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //在此处写入您的处理程序实现。
        context.Response.ContentType = "text/html";//这里一定要html

        string time = DateTime.Now.ToString("yyyyMMddHHmmssffff");
        var files = context.Request["file"];
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file = context.Request.Files[0];
            if (file.ContentLength > 0)
            {
                int length = file.FileName.Length;
                int dianLength = file.FileName.LastIndexOf('.');
                string filename = file.FileName.Substring(0, dianLength);
                string suffix = file.FileName.Substring(file.FileName.LastIndexOf('.'));//后缀
                if (".jpg.png.gif.jpeg".IndexOf(suffix.ToLower()) == -1)//文件格式,这里采用图片格式说明
                {
                    context.Response.Write("{\"msg\":\"文件格式不正确!\",\"code\":\"10001\"}");
                    return;
                }

                try
                {
                    file.SaveAs(context.Server.MapPath("~/uploadfile/") + filename+time+suffix);
                    context.Response.Write("{\"msg\":\"" + filename+time+suffix + "\",\"code\":\"10000\"}");
                    return;
                }
                catch (Exception ex)
                {
                    context.Response.Write("{\"msg\":\"" + HttpUtility.HtmlEncode(ex.Message) + "\",\"code\":\"10001\"}");
                    return;
                }
            }
            context.Response.Write("{\"msg\":\"请选择要上传的文件!\",\"code\":\"10001\"}");
            return;
        }
        context.Response.Write("{\"msg\":\"请选择要上传的文件!\",\"code\":\"10001\"}");
        return;

    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private static readonly object writeFile = new object();
    public static void WriteLog(string debugstr)
    {
        lock (writeFile)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                //服务器中日志目录
                string folder = HttpContext.Current.Server.MapPath("~/Log");
                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);
                fs = new FileStream(folder + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(DateTime.Now.ToString() + "     " + debugstr + "\r\n");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Flush();
                    sw.Dispose();
                    sw = null;
                }
                if (fs != null)
                {
                    //     fs.Flush();
                    fs.Dispose();
                    fs = null;
                }
            }
        }
    }

}

效果图【因为本身就有框架,所以这些只是实现文件上传 预览 上传的功能代码】
因为本身就有框架,所以这些只是实现文件上传 预览 上传的功能代码

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值