C# 附件上传

一、微软自带

界面

html:

<td align="center">
                    照片上传
                </td>
                <td>
                    <p id="myFiles">
                        <asp:FileUpload ID="fup_files" runat="server" class="TextBox form-control display-inline"
                            Style="width: 60%;" type="file" /><img runat="server" id="images" src="../../../images/4.png"
                                width="34" height="34"><br />
                        <font color="red">照片名为字母、数字</font> <span id="insert"></span>
                    </p>
                </td>

.cs代码:

        /// <summary>
        /// 附件保存
        /// </summary>
        private void AddFile()
        {
            if (fup_files.HasFile)
            {
                string path = "/Files/";
                if (!Directory.Exists(Server.MapPath(path)))
                {
                    Directory.CreateDirectory(Server.MapPath(path));
                }
                fup_files.SaveAs(Server.MapPath(path) + fup_files.FileName);
                path_temp = path + fup_files.FileName;
            }
        }

二、Js

界面:

html:

<table width="100%">
                    <tr>
                        <td>
                            <a href="javascript:;" class="files">
                                <input type="file" id="FileUpload2" name="FileUpload2" οnchange="AttachUpload2('AttachList','FileUpload2');" /></a>
                            <span class="uploading">正在上传,请稍候...</span>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div id="AttachList" class="attach_list">
                                <ul>
                                    <asp:Repeater ID="rptAttach" runat="server">
                                        <ItemTemplate>
                                            <li>
                                                <input name="hidFileName" type="hidden" value="<%#Eval("size")%>|<%#Eval("title")%>|<%#Eval("filepath")%>" />
                                                <b class="close1" title="删除" οnclick="DelAttachLi(this);">删除</b>                                          
                                                <span class="title">附件:<a style="text-decoration: underline; color: blue" href='personal_document_down.aspx?p=<%#Eval("filepath")%>' title="点击可下载"  id="a_uploadfile"><%#Eval("title")%></a></span>
                                                <span class="fsize">
                                                    <%#Eval("size")%></span>
                                                <a href="javascript:;" class="upfile"><input type="file" name="FileUpdate" οnchange="AttachUpdate('hidFileName',this);" /></a><span
                                                        class="uploading">正在更新...</span> </li>
                                        </ItemTemplate>
                                    </asp:Repeater>
                                </ul>
                            </div>
                        </td>
                    </tr>
                </table>

JS:

function AttachUpload2(repath, uppath) {

    var submitUrl = "../../../tools/upload_ajax.ashx?action=AttachFile&UpFilePath=" + uppath;
    //开始提交
    $("#form1").ajaxSubmit({
        beforeSubmit: function (formData, jqForm, options) {
            //隐藏上传按钮
            $("#" + uppath).parent().hide();
            //显示LOADING图片
            $("#" + uppath).parent().nextAll(".uploading").eq(0).show();
        },
        success: function (data, textStatus) {
            if (data.msg == 1) {
                var listBox = $("#" + repath + " ul");
                var newLi = '<li>'
+ '<input name="hidFileName" type="hidden" value="' + data.mssite + '|' + data.mstitle + "|" + data.msgbox + '" />'
                + '<input name="txtbox" type="hidden" value="' + data.msgbox + '" />'
                + '<b class="close" title="删除" οnclick="DelAttachLi(this);"></b>'
                + '附件:<span class="title" name="mstitle">' + data.mstitle + '</span>'
                + '大小:<span name="mssite" class="fsize">' + data.mssite + '</span>'
                + '<a href="javascript:;" class="upfile"><input type="file" name="FileUpdate" οnchange="AttachUpdate2(\'hidFileName\',this);" /></a>'
                + '<span class="uploading">正在更新...</span>'
                + '</li>';
                listBox.append(newLi);

            }
            else {
                alert(data.msgbox);
            }
            $("#" + uppath).parent().show();
            $("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
            document.getElementById(uppath).value = "";
        },
        error: function (data, status, e) {
            alert("上传失败,错误信息:" + e);
            $("#" + uppath).parent().show();
            $("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
        },
        url: submitUrl,
        type: "post",
        dataType: "json",
        timeout: 600000
    });
};

.CS

 #region 上传附件处理=====================================
        private void AttachFile(HttpContext context)
        {
            string _upfilepath = context.Request.QueryString["UpFilePath"]; //取得上传的对象名称
            HttpPostedFile _upfile = context.Request.Files[_upfilepath];
          
            bool _iswater = false; //默认不打水印
            bool _isthumbnail = false; //默认不生成缩略图

            if (_upfile == null)
            {
                context.Response.Write("{\"msg\": 0, \"msgbox\": \"请选择要上传文件!\"}");
                return;
            }
            Upload upFiles = new Upload();
            
            string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater, false, true);
            //返回成功信息
            context.Response.Write(msg);
            context.Response.End();
        }

#end

 public class Upload {
        /// <summary>
        /// 文件上传方法C
        /// </summary>
        /// <param name="postedFile">文件流</param>
        /// <param name="isThumbnail">是否生成缩略图</param>
        /// <param name="isWater">是否打水印</param>
        /// <param name="isReOriginal">是否返回文件原名称</param>
        /// <returns>服务器文件路径</returns>
        public string fileSaveAs(HttpPostedFile postedFile,bool isThumbnail,bool isWater,bool _isImage,bool _isReOriginal) {
            try {

                string fileExt = GetFileExt(postedFile.FileName); //文件扩展名,不含“.”
                string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得文件原名
                //string fileName = GetRamCode() + "." + fileExt; //随机文件名
                if(originalFileName.Contains(",") || originalFileName.Contains(","))   //去掉文件名中的,和,
                {
                    originalFileName = originalFileName.Replace(",","").Replace(",","");
                }
                string fileName = originalFileName;
                string dirPath = GetUpLoadPath(); //上传目录相对路径

                //检查文件扩展名是否合法
                if(!CheckFileExt(fileExt)) {
                    return "{\"msg\": 0, \"msgbox\": \"不允许上传" + fileExt + "类型的文件!\"}";
                }

                //检查是否必须上传图片
                if(_isImage && !IsImage(fileExt)) {
                    return "{\"msg\": 0, \"msgbox\": \"对不起,仅允许上传图片文件!\"}";
                }
                //检查文件大小是否合法
                if(!CheckFileSize(fileExt,postedFile.ContentLength)) {
                    return "{\"msg\": 0, \"msgbox\": \"文件超过限制的大小啦!\"}";
                }

                //获得要保存的文件路径
                string serverFileName = dirPath + fileName;
                string serverThumbnailFileName = dirPath + "small_" + fileName;
                string returnFileName = serverFileName;
                //物理完整路径                   
                string toFileFullPath = GetMapPath(dirPath);
                //检查有该路径是否就创建
                if(!Directory.Exists(toFileFullPath)) {
                    Directory.CreateDirectory(toFileFullPath);
                }
                //保存文件
                //判断文件是否存在,存在在后面名字追加1
                string newpath = GetNewPathForDupes(toFileFullPath + fileName);
                postedFile.SaveAs(newpath);

                long FactSize = postedFile.ContentLength;
                string m_strSize = "";
                if(FactSize < 1024.00)
                    m_strSize = FactSize.ToString("F2") + " Byte";
                else if(FactSize >= 1024.00 && FactSize < 1048576)
                    m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
                else if(FactSize >= 1048576 && FactSize < 1073741824)
                    m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
                else if(FactSize >= 1073741824)
                    m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";

                string tmpFilename = dirPath + Path.GetFileName(newpath);
                //如果需要返回原文件名
                if(_isReOriginal) {
                    return "{\"msg\": 1, \"msgbox\": \"" + tmpFilename + "\", \"mstitle\": \"" + originalFileName + "\",\"mssite\":\"" + m_strSize + "\"}";
                }
                return "{\"msg\": 1, \"msgbox\": \"" + tmpFilename + "\",\"mssite\":\"" + m_strSize + "\"}";
            } catch {
                return "{\"msg\": 0, \"msgbox\": \"上传过程中发生意外错误!\"}";
            }
        }

        #region 获得当前绝对路径
        /// <summary>
        /// 返回文件扩展名,不含“.”
        /// </summary>
        /// <param name="_filepath">文件全名称</param>
        /// <returns>string</returns>
        public static string GetFileExt(string _filepath) {
            if(string.IsNullOrEmpty(_filepath)) {
                return "";
            }
            if(_filepath.LastIndexOf(".") > 0) {
                return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
            }
            return "";
        }
        /// <summary>
        /// 生成日期随机码
        /// </summary>
        /// <returns></returns>
        public static string GetRamCode( ) {
            #region
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            #endregion
        }
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath) {
            if(strPath.ToLower().StartsWith("http://")) {
                return strPath;
            }
            if(HttpContext.Current != null) {
                return HttpContext.Current.Server.MapPath(strPath);
            } else //非web程序引用
            {
                strPath = strPath.Replace("/","\\");
                if(strPath.StartsWith("\\")) {
                    strPath = strPath.Substring(strPath.IndexOf('\\',1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,strPath);
            }
        }
        #endregion
        /// <summary>
        /// 返回上传目录相对路径
        /// </summary>
        /// <param name="fileName">上传文件名</param>
        private string GetUpLoadPath( ) {
            string path = "/attach_upload/"; //站点目录+上传目录
            switch(2) {
                case 1: //按年月日每天一个文件夹
                    path += DateTime.Now.ToString("yyyyMMdd");
                    break;
                default: //按年月/日存入不同的文件夹
                    path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
                    break;
            }
            return path + "/";
        }
        /// <summary>
        /// 是否为图片文件
        /// </summary>
        /// <param name="_fileExt">文件扩展名,不含“.”</param>
        private bool IsImage(string _fileExt) {
            ArrayList al = new ArrayList();
            al.Add("bmp");
            al.Add("jpeg");
            al.Add("jpg");
            al.Add("gif");
            al.Add("png");
            if(al.Contains(_fileExt.ToLower())) {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 检查是否为合法的上传文件
        /// </summary>
        private bool CheckFileExt(string _fileExt) {
            //检查危险文件
            string[] excExt = { "asp","aspx","php","jsp","htm","html" };
            for(int i = 0;i < excExt.Length;i++) {
                if(excExt[i].ToLower() == _fileExt.ToLower()) {
                    return false;
                }
            }
            //检查合法文件   限制上传文件  王景波 2012.06
            //string[] allowExt = this.siteConfig.attachextension.Split(',');
            //for (int i = 0; i < allowExt.Length; i++)
            //{
            //    if (allowExt[i].ToLower() == _fileExt.ToLower())
            //    {
            //        return true;
            //    }
            //}
            return true;
        }

        /// <summary>
        /// 检查文件大小是否合法
        /// </summary>
        /// <param name="_fileExt">文件扩展名,不含“.”</param>
        /// <param name="_fileSize">文件大小(KB)</param>
        private bool CheckFileSize(string _fileExt,int _fileSize) {
            判断是否为图片文件
            //if (IsImage(_fileExt))
            //{
            //    if (10240 > 0 && _fileSize > this.siteConfig.attachimgsize * 1024)
            //    {
            //        return false;
            //    }
            //}
            //else
            //{
            //    if (this.siteConfig.attachfilesize > 0 && _fileSize > this.siteConfig.attachfilesize * 1024)
            //    {
            //        return false;
            //    }
            //}
            return true;
        }
        private string GetNewPathForDupes(string path) {
            string directory = Path.GetDirectoryName(path);
            string filename = Path.GetFileNameWithoutExtension(path);
            if(filename.Contains(",") || filename.Contains(",")) {
                filename = filename.Replace(",","").Replace(",","");
            }
            string extension = Path.GetExtension(path);
            int counter = 1;

            string newFullPath;

            do {
                string newFilename = string.Format("{0}({1}){2}",filename,counter,extension);
                newFullPath = Path.Combine(directory,newFilename);
                counter++;
            } while(System.IO.File.Exists(newFullPath));

            return newFullPath;
        }
    }

 

检测指定目录是否存在, 检测指定文件是否存在, 如果存在则返回true, 获取指定目录中所有文件列表,获取指定目录中所有子目录列表, 取指定目录及子目录中所有文件列表, 指定目录的绝对路径,检测指定目录是否为空, 检测指定目录中是否存在指定的文件, 若要搜索子目录请使用重载方法., 检测指定目录中是否存在指定的文件, 创建目录, 删除目录, 创建文件, 移动文件(剪贴--粘贴), 复制文件, 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff, 根据时间得到文件名HHmmssff, 根据时间获取指定路径的 后缀名的 的所有文件, 复制文件夹,检查文件, 如果文件不存在则创建, 删除指定文件夹对应其他文件夹里的文件, 从文件的绝对路径中获取文件名( 包含扩展名 ), 复制文件参考方法,页面中引用, 创建一个目录, 创建一个文件, 并将字节流写入文件, 获取文本文件的行数, 获取一个文件的长度, 单位为Byte, 获取文件大小并以B,KB,GB,TB, 获取指定目录中的子目录列表, 向文本文件写入内容, 向文本文件的尾部追加内容, 将现有文件的内容复制到新文件中, 将文件移动到指定目录, 从文件的绝对路径中获取文件名( 不包含扩展名 ), 从文件的绝对路径中获取扩展名 以上每一行为一个方法, 例子如下: #region 清空指定目录 /// /// 清空指定目录下所有文件及子目录,但该目录依然保存. /// /// 指定目录的绝对路径 public static void ClearDirectory(string directoryPath) { directoryPath = HttpContext.Current.Server.MapPath(directoryPath); if (IsExistDirectory(directoryPath)) { //删除目录中所有的文件 string[] fileNames = GetFileNames(directoryPath); for (int i = 0; i < fileNames.Length; i++) { DeleteFile(fileNames[i]); } //删除目录中所有的子目录 string[] directoryNames = GetDirectories(directoryPath); for (int i = 0; i < directoryNames.Length; i++) { DeleteDirectory(directoryNames[i]); } } } #endregion #region 清空文件内容 /// /// 清空文件内容 /// /// 文件的绝对路径 public static void ClearFile(string filePath) { //删除文件 File.Delete(filePath); //重新创建该文件 CreateFile(filePath); } #endregion #region 删除指定目录 /// /// 删除指定目录及其所有子目录 /// /// 指定
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值