• ajax无刷新上传


    我们在使用上传控件的时候,会遇到刷新的问题,最近使用ajax做的上传,觉得效果还是很不错。

    首先,我们需要在页面上放上上传控件;需要注意的是,我们必须放在form里面,实现表单上传。

     <form class="picForm" name="uploadPic" enctype="multipart/form-data">
            选择图片:<input type="file" class="file" name="picture" /><br />
     </form>

     前台提交方法

    function TajaxFileUpload() {
                   var mypath = "../ajax/upload.ashx?fileName="+需要的参数;
                    $("form[name='uploadPic']").ajaxSubmit({
                        url: mypath,
                        type: 'POST',
                        success: function (html, status) {
                            if (status == "success") {
                                html = html.replace(/</?[^>]*>/g, '');
                                //html = html.replace(/[ | ]*
    /g, '
    ');
                                var json = eval('(' + html + ')');
                                if (json.state == "success") {
    //上传成功 }
    else {//上传失败 } }
    else { art.dialog.alert("请求数据失败"); } //stauts success } //submit success }); //ajaxSubmit } //t ajax

     upload.ashx代码如下

    using System;
    using System.IO;
    using System.Web;
    using System.Text;
    using System.Net;
    
    namespace BatchImageUpload
    {
        /// <summary>
        /// Summary description for upload
        /// </summary>
        public class upload : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                try
                {
                    if (context.Request.Files["picture"] == null)
                    {
                        //图片控件中没有选择图片
                        context.Response.Write("{state:'error',msg:'您还未选择图片'}");
                    }
                    else
                    {
    
                        string fileName = context.Request.QueryString["fileName"];
                        HttpPostedFile pic = context.Request.Files["picture"];
                        string foldPath = HttpContext.Current.Server.MapPath("/") + @"OrderUserInfoImages";
                        foldPath = foldPath + fileName;
                        DirectoryInfo di = new DirectoryInfo(foldPath);
                        if (!di.Exists)//如果文件夹目录不存在
                        {
                            di.Create();//新建文件夹
                        }
                        string imageName = UpLoadImage(pic, foldPath);
                        context.Response.Write("{state:'success',msg:'上传成功:" + imageName + "'}");
    
    
    
    
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Write("{state:'error',msg:'" + ex.Message + "'}");
                }
            }
    
            #region 上传图片
            /// <summary>
            /// 上传图片
            /// </summary>
            /// <param name="imgfile">文件http流</param>
            /// <param name="nowpath">所需放置的文件路径</param>
            /// <returns>上传成功,返回字符串,否则,抛出异常</returns>
            public static string UpLoadImage(HttpPostedFile imgfile, string nowpath)
            {
                try
                {
                    string serverPath = System.Web.HttpContext.Current.Server.MapPath("~");
    
                    string toFilePath = Path.Combine(serverPath, nowpath);
    
                    //获取要保存的文件信息
                    FileInfo file = new FileInfo(imgfile.FileName);
                    //获得文件扩展名
                    string fileNameExt = file.Extension;
    
                    //验证合法的文件
                    if (CheckImageExt(fileNameExt))
                    {
                        //生成将要保存的随机文件名
                        string fileName = GetImageName() + fileNameExt;
    
                        //获得要保存的文件路径
                        string serverFileName = toFilePath + fileName;
                        //物理完整路径                    
                        string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath);
    
                        //将要保存的完整文件名                
                        string toFile = toFileFullPath;//+ fileName;
    
                        ///创建WebClient实例       
                        WebClient myWebClient = new WebClient();
                        //设定windows网络安全认证   方法1
                        myWebClient.Credentials = CredentialCache.DefaultCredentials;
                        ////设定windows网络安全认证   方法2
                        imgfile.SaveAs(toFile);
     
                        string relativePath =fileName;
                        return relativePath;
                    }
                    else
                    {
                        throw new Exception("文件格式非法,请上传gif|jpg|bmp|png格式的文件。");
                    }
                }
                catch
                {
                    throw;
                }
            }
            #endregion
    
            #region 图片上传格式和文件名
            /// <summary>
            /// 检查是否为合法的上传图片
            /// </summary>
            /// <param name="_fileExt"></param>
            /// <returns></returns>
            public static bool CheckImageExt(string _ImageExt)
            {
                string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
                for (int i = 0; i < allowExt.Length; i++)
                {
                    if (string.Compare(allowExt[i], _ImageExt, true) == 0)
                    { return true; }
                }
                return false;
    
            }
    
            private static string GetImageName()
            {
                Random rd = new Random();
                StringBuilder serial = new StringBuilder();
                serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
                serial.Append(rd.Next(0, 999999).ToString());
                return serial.ToString();
    
            }
    
            #endregion
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

     单文件上传只需要按照这个方法就可以。如果要做到批量上传,需要动态添加上传控件,然后遍历上传控件坐上传功能即可

  • 相关阅读:
    JavaSE—集合框架
    JavaSE——集合框架
    RocketMq 在Netty 下是如何进行消息封装传输
    SpringBoot 初始化流程以及各种常见第三方配置的源码实现
    Java 重要知识点,踩过的坑
    Mysql 知识储备以及InnoDB
    java 编程英语单词,语句
    PlantUML
    Rocketmq broker 消息仓库
    AutowiredAnnotationBeanPostProcessor 的一些思考
  • 原文地址:https://www.cnblogs.com/panshengqiang/p/3195631.html
Copyright © 2020-2023  润新知