代码改变世界

ASP.NET上传下载文件

2012-02-11 21:21  javaspring  阅读(177)  评论(0编辑  收藏  举报

ASP.NET上传下载文件

上传文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO; 
#region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="UpLoadFilePath">上传位置</param>
        /// <param name="strTime">当前时间(加时间重命名文件,防止重复)</param>
        /// <param name="upload">上传控件</param>
        private void UploadMethod(String UpLoadFilePath, string strTime,FileUpload upload)
        {
            bool fileOK = false;

            //文件的上传路径
            string path = Server.MapPath(UpLoadFilePath);

            //判断上传文件夹是否存在,若不存在,则创建
            if (!Directory.Exists(path))
            {
                //创建文件夹 
                Directory.CreateDirectory(path);
            }
            //如果选择了文件则执行
            if (upload.HasFile)
            {
               
                //获取上传文件的类型
                string fileExtesion = System.IO.Path.GetExtension(upload.FileName).ToLower();
                //获取没有扩展名的文件名
                string result = System.IO.Path.GetFileNameWithoutExtension(upload.FileName);

                //允许上传的类型
                string[] allowExtesions = { ".doc", ".xls", ".rar", ".zip", ".ppt" };
                for (int i = 0; i < allowExtesions.Length; i++)
                {
                    if (fileExtesion == allowExtesions[i])
                    {
                        //文件格式正确 允许上传
                        fileOK = true;
                    }
                }

                if (fileOK)
                {
                    try
                    {
                       string  newname = result + strTime + fileExtesion;
                       upload.PostedFile.SaveAs(path + newname);
                       Session["filename"] = newname;
                    }
                    catch (Exception)
                    {
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('上传失败!');</script>");
                    }
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('上传失败!');</script>");
                }
            }
            else
            {
                //尚未选择文件
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('尚未选择任何文件,请选择文件!');</script>");
                return;
            }
        }
        #endregion

下载文件:

   using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downloadfilepath">文件路径</param>
        private void DownloadMethod(string downloadfilepath)
        {
            string path = Server.MapPath(downloadfilepath);

            Regex re = new Regex(@"\w*\.\w*");
            string st = re.Match(path).Value.ToString();
            string fileName = st; //客户端保存的文件名

            FileInfo fileInfo = new FileInfo(path);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }

调用:

    UploadMethod(DocPath,strTime,fileUpload);

    DownloadMethod(filePath);