C#文件上传类,非常好用.

来源:互联网 发布:大华软件测试面试 编辑:程序博客网 时间:2024/05/16 14:24

1.文件上操作BLL类:

using System;
using System.Collections.Generic;
using System.Text;

namespace BLL
{
    public class UploadOperation
    {
        //public string upload(string path, System.Web.UI.HtmlControls.HtmlInputFile UpFile, string docType)
        public string upload(string path, System.Web.UI.WebControls.FileUpload UpFile, string docType)

        {
            string Path = "";
            if (path.Trim() != "")
            {
                Path = System.Web.HttpContext.Current.Request.ApplicationPath + "/" + path + @"/";
            }
            else
            {
                Path = System.Web.HttpContext.Current.Request.ApplicationPath + "/" + System.Configuration.ConfigurationSettings.AppSettings["DocPath"].ToString() + @"/";
            }
            BLL.FileUpload Upload = new BLL.FileUpload();
            return Upload.Upload(Path, UpFile, docType);
        }

        public void DeleteFiles(string path,string fileName)
        {
            BLL.FileUpload Upload = new BLL.FileUpload();
            string fullPath = System.Web.HttpContext.Current.Request.ApplicationPath + "/" + System.Configuration.ConfigurationSettings.AppSettings["DocPath"].ToString() + path;
            int exsits = Upload.SearchFile(System.Web.HttpContext.Current.Request.ApplicationPath + "/" + System.Configuration.ConfigurationSettings.AppSettings["DocPath"].ToString() + path, fileName);
            if (exsits == 1)
            {
                Upload.DeleteFile(fullPath + "//" + fileName);
            }
        }
    }
}
2.文件操作DAL类:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;


namespace BLL
{
    public class FileUpload
    {
       /// <summary>
       /// Upload file
       /// </summary>
       /// <param name="path">The path of folder you want to put the file</param>
        /// <param name="UpFile">A entity of class HtmlInputFile</param>
       /// <param name="docType">Allowed file type</param>
        /// <returns>Result of upload</returns>
        //public  string Upload(string path,System.Web.UI.HtmlControls.HtmlInputFile UpFile,string docType)
        public string Upload(string path, System.Web.UI.WebControls.FileUpload UpFile, string docType)

        {
            string modifyFileName = DateTime.Now.Year.ToString();
            modifyFileName += DateTime.Now.Month.ToString();
            modifyFileName += DateTime.Now.Day.ToString();
            modifyFileName += DateTime.Now.Hour.ToString();
            modifyFileName += DateTime.Now.Minute.ToString();
            modifyFileName += DateTime.Now.Second.ToString();
            modifyFileName += DateTime.Now.Millisecond.ToString();
            string value = UpFile.FileName;
            string tFileType = value.Substring(value.LastIndexOf(".") + 1);
            string[] allowedType = docType.Split(',');
            bool TypeMatched = false;
            if (value == "" || value == null)
            {
                return "-1";             //Error:Uploaded file is null!
            }
            else
            {
                int FileLength = UpFile.PostedFile.ContentLength;
                if (FileLength > (20 * 1024 * 1024))
                {
                    return "-2";        //Error:Uploaded file is too large!
                }
                foreach (string type in allowedType)
                {
                    if (type.ToLower().IndexOf(tFileType) != -1)
                    {
                        TypeMatched = true;
                    }
                }
                if (!TypeMatched)
                {
                    return "-3"; //Error:Wrong type of Uploaded file!
                }
                string dirPath = System.Web.HttpContext.Current.Server.MapPath(path);
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(dirPath);
                if (!dir.Exists)
                {
                   dir.Create();
                }
                path = path + modifyFileName + "." + tFileType;
                UpFile.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                return System.Web.HttpContext.Current.Server.MapPath(path);     //Upload succeed!
            }
        }

       /// <summary>
       /// Search a file from the mapped path
       /// </summary>
       /// <param name="path">The mappsed path</param>
       /// <param name="fileName">The file name for search</param>
       /// <returns>Result of search</returns>
        public  int SearchFile(string path,string fileName)
        {
            System.IO.DirectoryInfo SearchDir = new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path));
            foreach (System.IO.FileInfo File in SearchDir.GetFiles())
            {
                if (File.Name.IndexOf(fileName) != -1)
                {
                    return 1;// Find
                }
            }
            return 0;//Not find
        }
        /// <summary>
        /// Delete a file
        /// </summary>
        /// <param name="path">The path of file</param>
        /// <returns>The result of delete</returns>
        public int DeleteFile(string path)
        {
            System.IO.FileInfo File = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
            if (File.Exists)
            {
                if (File.IsReadOnly)
                {
                    return -1;//The file is readonly
                }
                else
                {
                    File.Delete();
                    return 1;//Delete succeed
                }
            }
            else
            {
                return 0;//The file is not exsits
            }
        }

        public int FileMove(string sFolder, string sName, string tFolder, string tName)
        {
            string[] arrDirs = Directory.GetDirectories(sFolder);
            string[] arrFiles = Directory.GetFiles(sFolder);

            if (arrFiles.Length != 0)
            {
                //copy this file
                File.Copy(sFolder + "//" + sName, tFolder + "//" + tName, true);

                //delete the old file
                return DeleteFile(sFolder + "//" + sName);

            }
            else
            {
                return -1;
            }
           

        }

        public void FileMove(string sFolder, string tFolder)
        {
            string[] arrDirs = Directory.GetDirectories(sFolder);
            string[] arrFiles = Directory.GetFiles(sFolder);

            if (arrFiles.Length != 0)
            {
               
                for (int i = 0; i < arrFiles.Length; i++)
                {
                    //copy these files
                    File.Copy(sFolder + "//" + Path.GetFileName(arrFiles[i]), tFolder + "//" + Path.GetFileName(arrFiles[i]), true);

                    //delete old files
                    DeleteFile(sFolder + "//" + Path.GetFileName(arrFiles[i]));
                }             

            }
        }
    }
}

3.前台代码

    <div class="NewUserRowFrame2">
                        <div class="NewUserTextFrame" style="width: 53px">
                            图片展示:
                        </div>
                         <div class="NewUserTextBoxFrame" style="width: 218px">
                           <asp:FileUpload ID="AddUP" runat="server" Font-Size="14px" Height="20px" Width="174px" />
                        <input type="button" value="提交" onclick="ValidateMoldInformation()" style="height: 21px" /></div>

                    </div>
                    <div id="AddMoldInformationFrame" class="NewUserRowFrame" style="font-size:10px;padding-right:10px;color:Red; " runat="server">
                        
                    </div> 
                    <div class="NewUserRowFrame2" id="AddimgShow" style="visibility:hidden" >
                            <asp:Image ID="AddImg" runat="server" Height="137px" Width="136px"  />
                    </div>


                    <div class="NewUserRowFrame">
                        &nbsp;<asp:Button ID="Button1" runat="server" Text="提交" style="display:none" OnClick="Button1_Click"/>

                    </div>

 

5.后台上传,删除按钮代码:

    //上传

    protected void Button1_Click(object sender, EventArgs e)
    {
        BLL.UploadOperation Upload = new BLL.UploadOperation();
        string i = Upload.upload("", this.AddUP, "PNG,JPG,TIF,GIF,BMP");
        if (i == "-1")
        {
            Response.Write("<script>alert('请选择需要上传的图片!')</script>");
        }
        if (i == "-2")
        {
            Response.Write("<script>alert('图片太大无法上传!')</script>");
        }
        else if (i == "-3")
        {
            Response.Write("<script>alert('图片类型不正确!!')</script>");
        }
        else
        {
            string ImgName = "";
            if (i != "-1")
            {
                string Uppath = AddUP.FileName;
                int index = Uppath.LastIndexOf("//");
                int index2 = Uppath.LastIndexOf('.');
                string trueName = Uppath.Substring(index + 1, index2 - index - 1);
                string pathInDb = i.Substring(i.LastIndexOf("//"));

                ImgName = pathInDb.Remove(0, 1);//写入到数据库的名字
            }
            Response.Write("<script>alert('信息添加成功!!!')</script>");

            ClientScript.RegisterClientScriptBlock(this.GetType(), "closeWindow", "CloseWindowReflash()", true);

        }
    }

    //删除

                BLL.UploadOperation Up = new BLL.UploadOperation();

                Up.DeleteFiles("", ds.Tables[0].Rows[0]["xxx"].ToString());

6.后台加载预览功能,注册前台方法

    if (!IsPostBack)
        {
            this.AddUP.Attributes.Add("onChange", "changeSearchText();document.getElementById('" + this.AddImg.ClientID + "').src=document.getElementById('" + this.AddUP.ClientID + "').value");
        }

 

前台javascript

 function changeSearchText()
        {  
            document.getElementById('AddimgShow').style.visibility='visible';  
        }

7.web.config添加提交路径

 <appSettings>
  <add key="DocPath" value="/UploadFiles/img/"/>
 </appSettings>