fileupload控件上传、文件下载

本文详细介绍了文件上传和下载的实现过程,包括图片格式验证、服务器上传逻辑、下载服务端文件的方法,以及更加简洁的下载方式。适用于网站开发中处理文件交互的需求。

常遇到上传下载的功能,这里把我习惯的用法写下来:

上传:

string fileName = "";
fileName = this.fu_pic.FileName;
if (string.IsNullOrEmpty(fileName))
  isPic = "0";
else
  isPic = "1";

//附件不为空的时候上传图片,否则不处理
if (isPic == "1")
{
  byte[] arrayByte = this.fu_pic.FileBytes;
  if (arrayByte.Length <= 0)
  {
    //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片是空文件!')</script>");
    AlertMessage("上传图片是空文件!");
    this.fu_pic.Focus();
    return;
  }

  string extention = fileName.Substring(fileName.LastIndexOf(".") + 1);
  if (extention.ToUpper() != "JPG"
                    && extention.ToUpper() != "BMP"
                    && extention.ToUpper() != "PNG"
                    && extention.ToUpper() != "GIF")
  {
    //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式错误,请上传jpg/bmp/png/gif格式图片!')</script>");
    AlertMessage(@"图片格式错误,请上传jpg/bmp/png/gif格式图片!");
    this.fu_pic.Focus();
    return;
  }
  else
  {
    //按照年/月 生成文件目录
    fileName = string.Format(@"UploadImage\{0}\{3}\{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.ToString("yyyyMMddHHmmssfff"), fileName, DateTime.Now.Month.ToString());
    //获取附件上传物理路径(这里设置在config文件中)
    string dePath = ConfigurationManager.AppSettings["upload"].ToString();
    string filePath = Path.Combine(dePath, fileName);//Server.MapPath(@".." + fileName);//外面一层就是网站目录
    if (saveView(arrayByte, filePath))
    {
      //saveAttach = true;

    }
    else
    {
      //saveAttach = false;
      //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片上传服务器失败!')</script>");
      AlertMessage("图片上传服务器失败!");
      this.fu_pic.Focus();
      return;
    }
  }
}

public bool saveView(byte[] arry_byte, string filePath)
    {
        bool rst = false;
        FileStream saveStream = null;
        try
        {
            //判断文件夹是否存在
            FileInfo file = new FileInfo(filePath);
            if (!file.Exists)
            {
                if (!Directory.Exists(file.DirectoryName))
                    Directory.CreateDirectory(file.DirectoryName);
            }
            file = null;

            //保存文件
            saveStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            saveStream.Write(arry_byte, 0, arry_byte.Length);
            saveStream.Close();
            rst = true;
        }
        catch (Exception)
        {
            rst = false;
        }

        return rst;
    }

 

下载保存:

/// <summary>
        /// 下载服务端文件
        /// </summary>
        /// <param name="fileName">下载时客户端显示名称</param>
        /// <param name="filePath">服务端文件完全物理路径</param>
        /// <returns></returns>
        public void DownloadFile(string fileName, string filePath)
        {
            //服务端文件是否存在
            if (File.Exists(filePath))
            {
                FileInfo fi = new FileInfo(filePath);
                long length = fi.Length;

                //读取文件到流sr中,using为防止文件被进程占据,强制释放资源
                using (FileStream sr = new FileStream(filePath, FileMode.Open))
                {
                    int startlength = 0;
                    int bufferSize = 1;
                    byte[] buffer = new byte[bufferSize];
                    byte[] allBuffer = new byte[length];

                    //循环读取流到allBuffer中
                    while (startlength < length)
                    {
                        //读取bytes个字节到buff中的0到bufferSize位置
                        //sr.read后,sr自动移动到读取的位置
                        int bytes = sr.Read(buffer, 0, bufferSize);

                        //将buff内容存入allBuffer中
                        allBuffer[startlength] = buffer[0];

                        //前进bytes个位置
                        startlength += bytes;
                    }

                    //清空缓存中的流
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();

                    //输出流
                    Response.AddHeader("Accept-Ranges", "bytes");
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("gb2312")));
                    Response.BinaryWrite(allBuffer);
                    Response.Flush();
                    Response.End();
                }
            }
        }

更加简洁的下载:

 string fileName = "日志.txt";
            string txtFullFilePath = "c:/test/aa.txt";

            if (File.Exists(Server.MapPath(txtFullFilePath)))
            {
                //文件对象
                FileInfo fileInfo = new FileInfo(Server.MapPath(txtFullFilePath));
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(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();
            }

转载于:https://www.cnblogs.com/maomaokuaile/p/3503176.html

由于OA系统是基于WEB方式的,如果只判断用户是否点击“下载文件”,就来判断用户是否成功下载文件。这种方式很显然行不通,怎么办呢?我想到的就是用一控件,然后用回调事件来处理数据库方面的问题(下载记录问题) 有兴趣的朋友可在 http://www.interdrp.com/ 下载分销系统 用测试帐号进系统后,点测试程序,再点WEB下载 可以看见效果 https://www.interdrp.com/software/ReYoWebDownLoad.zip(点击下载控件) API说明 ReYoWebDL.copyright="锐洋软件拥有版权 http://www.interdrp.com/" //必须 ReYoWebDL.url="http://dl.baofeng.com/storm3/Storm2009-0504-1.exe" //下载文件的路径 ReYoWebDL.path ="" //保存文件地址 ReYoWebDL.ReYoStartDownload() //下载动作 ReYoWebDL.ReYoStopDownload() //停止下载 ReYoWebDL.size //下载文件大小 ReYoWebDL.bytes//已下载大小 ReYoWebDL.speed //下载速度 KB/S ReYoWebDL.done //下载是否完成 ReYoWebDL.cancle=true; //是否取消下载 ReYoWebDL.urlsource //下载文件名 ReYoWebDL.percent //下载百分比 升级提示: 20090506:新增剩余时间,下载百分比进度,下载速度及文件保存位置显示;且支持断点续传功能。 20090504:新增下载过程序取消下载动作。 20090502:新增文件存在提示。 目前控件支持两种方式下载: 1:开发者在程序中指定下载文件的url,保存文件的path。例如:download("http://www.interdrp.com/software/hotel/setup.zip","c:\a.zip" 2:开发者在程序中指定下载文件的url,不指定保存文件的path,系统会提示您选择保存文件的路径。例如:download("http://www.interdrp.com/software/hotel/setup.zip",""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值