.net利用ajax技术实现图片上传并回显到界面

来源:互联网 发布:六边形战士 知乎 编辑:程序博客网 时间:2024/04/30 19:12

最近在开发过程中遇到了一个非常郁闷的问题,就是图片传到fileUpload中时想要实现回显到image控件中。

在前台,fileUpload.change()事件中判断fileUpload.val()不为空,把改路径值赋给image.attr("src",$('#fileUpload的ID').val()),

IE和火狐都无法实现,反而2345王牌浏览器可以实现读取本地路径的功能,

再用ajax异步调用函数,获取本地路径后再返回本地路径,同样无法实现,估计是跟浏览器的权限有关。

那么重点开始了,现在采用其他思路试试吧。

先来给fileUpload的change事件绑定一个upload的javascript函数,

//上传照片        function upload() {            var u = "";            var options = {                url: "../services/upload.ashx",//处理程序路径                type: "post",                success: function (msg) {//回调函数--请求成功                    if (msg.toString().substring(0, 3) == "ERR") {//                        alert(msg.substring(3, msg.length));                    }                    else {                        $("#img_tx").attr("src", msg);//回显图片                    }                },                error:function(err){                    alert("123");            }            };            //将options传给ajaxForm            $('#form1').ajaxSubmit(options);        }

在这个函数中,我们调用了upload.ashx处理程序,该程序实现代码如下:

因为这里采用Session传递文件名,所以一定要引用IRequiresSessionState接口

同时添加下面三个引用

using System.Drawing;

using System.Web.SessionState;

using System.Web.Services;

public class upload : IHttpHandler,IRequiresSessionState
    {               /// <summary>        /// 上传照片        /// </summary>        /// <param name="context"></param>        public void ProcessRequest(HttpContext context)        {            HttpFileCollection files = context.Request.Files;            string path = "";//照片路径            bool errorflag = true;            string tishi = "";            if (files.Count > 0)//Form中获取文件对象            {                HttpPostedFile file = files[0];                if (file.ContentLength > 0)//文件大小大于零                {                    string fileName = file.FileName;//文件名                    int fileSize = file.ContentLength;//文件大小                    if (fileName.Substring(fileName.Length - 4, 4).ToLower() == ".jpg")//只支持.jpg文件上传                    {                        try                        {                            Bitmap bitmap = new Bitmap(file.InputStream);//获取图片文件                            if (bitmap.Width > 480 || bitmap.Height > 640)                            {                                errorflag = false;                                tishi = "照片太大,请将照片调整为320*240像素尺寸!";                            }                            if (bitmap.Width < 120 || bitmap.Height < 160)                            {                                errorflag = false;                                tishi = "照片太小,请将照片调整为320*240像素尺寸!";                            }                            if (bitmap.Width > bitmap.Height)                            {                                errorflag = false;                                tishi = "照片的宽度比不符合要求,请将高度比调整为4:3!";                            }                            if (fileSize > 100 * 1024)                            {                                errorflag = false;                                tishi = "照片的大小不符合要求,请将照片调整为100kb以内!";                            }                        }                        catch                        {                            errorflag = false;                            tishi = "照片错误,上传文件非图像文件!";                        }                    }                    else                    {                        errorflag = false;                        tishi = "照片格式错误,请上传JPG格式照片文件!";                    }                }            }            else            {                errorflag = false;                tishi = "照片错误,上传照片文件为0字节!";            }            if (errorflag)            {                string extension = ".jpg";                context.Session["zpname"] = Guid.NewGuid().ToString();//创建唯一文件名                path = "../zhaopian/" + context.Session["zpname"].ToString() + extension;//指定保存路径以及文件名,也就是完整相对路径                files[0].SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));//保存文件(将相对路径转化为绝对路径)                context.Response.Write(path);//相应给客户端该照片的相对路径            }            else            {                context.Response.Write("ERR" + tishi);            }        }
<span style="font-size:24px;background-color: rgb(255, 102, 102);"><strong>到这里,我们已经能够实现当用户选择路径之后回显到界面的功能了。</strong></span>
下面附加一个功能模块,将照片以及用户修改的信息添加到数据库中。
首先,看一下前台是如何使用ajax调用后台函数的:
<pre class="html" name="code">//Document.ready()        $(function () {             //保存用户修改信息            $('#b_xgxx').click(function () {                var upzp = false;//默认不上传照片                if ($('#fu_tx').val() != "") {//如果fileUpload有路径,就指定上传照片                    upzp = true;                }                $.ajax({                    url: "../services/WebService.asmx/modify_ZJXX",                    type: "post",                    contentType: "application/json;charset=utf-8",                    dataType: 'json',                    async: false,                    data: "{xm:'"+$('#t_xm').val()+"',sclydm:'"+$('#t_sclydm').val()+"',zhwt:'"+$('#t_zhwt').val()+"',zjjs:'"+$('#t_zjjs').val()+"',upzp:"+upzp+"}",                    success: function (response) {                        if (response.d != "") {                            alert(response.d);                        }                    },                    error:function(err){                        alert(err);                }                })            });
在提交按钮按下事件中,首先判断fu_tx是否有值,如果有就上传照片,如果没有,就不用上传照片,只上传其他信息
然后,看一下后台modefy_ZJXX函数的写法:
<p>[WebMethod(EnableSession = true)]        public string modify_ZJXX(string xm, string sclydm, string zhwt, string zjjs,bool upzp)        {            Model.T_ZHUANJIA model = (Model.T_ZHUANJIA)Session["ZJXX"];            string tishi = "";            if (upzp == true)            {                //获取图片信息                if (Session["zpname"].ToString().Trim() == "")                {                    tishi = "请选择需要上传的照片";                }                else                {                    //获取绝对路径                    string path = Server.MapPath("~/web/zhaopian/" + Session["zpname"].ToString() + ".jpg");                    //读取照片文件                    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);                    Byte[] bytes=new byte[fs.Length];                    fs.Read(bytes, 0, (int)fs.Length);                    fs.Dispose();//释放资源                    fs.Close();//关闭文件流                    model.ZJTX = bytes;//给专家头像变量赋值                    File.Delete(path);//删除服务器中的图片文件</p><p>                }            }            //获取修改的其他信息,并写入数据库            model.XM = xm;            model.SCLYDM = sclydm;            model.ZHWT = zhwt;            model.ZJJS = zjjs;            BLL.B_ZHUANJIA.UpdateZhuanJia(model, out tishi);//插入数据库中            return tishi;                    }</p><p>其中有部分变量未说明,这里只做主要思路的介绍,一些无关的变量可以不用考虑。</p>



 

0 0
原创粉丝点击