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

上传:

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();
            }

fileupload控件上传、文件下载的更多相关文章

  1. .net简单的fileupload控件上传

    前台代码: <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID ...

  2. WebForm使用FileUpload控件上传压缩二进制图片

    fuImage 是FileUpload页面控件 ImageHelper.CompressionImage(fuImage.FileBytes, quality); /// <summary> ...

  3. asp.net FileUpload 控件上传文件 以二进制的形式存入数据库并将图片显示出来

    图片上传事件代码如下所示: byte[] binary = upload.FileBytes; StringBuilder sqlStrSb = new StringBuilder(); sqlStr ...

  4. asp:FileUpload 控件上传多文件

    <asp:FileUpload runat="server" ID="imgUpload" AllowMultiple="true" ...

  5. FileUpload的控件上传excel

    在一个使用FileUpload的控件上传excel,读取excel的数据 因为上传的路径一直被限定在C:\Program\IIS\Express 一直限制这个文件下, 想要解决这个问题. 在谷歌浏览器 ...

  6. MVC项目使用easyui的filebox控件上传文件

    开发环境:WIN10+IE11,浏览器请使用IE10或以上版本 开发技术框架MVC4+JQuery Easyui+knockoutjs 效果为弹出小窗体,如下图 1.前端cshtml文件代码(只包含文 ...

  7. JS ajaxfileUpload 一次性上传多个input控件 上传多个文件

    本方法适用于一次性上传多个input框输入的文件,如下图所示,任务是需要一次上传两个input框提供的两个文件. 具体方法: 1.修改ajax调用方法 如上图所示,只需要将ajaxFileUpload ...

  8. c#上传文件(一)使用 .net 控件上传文件

    1.html代码: <body> <form id="form1" runat="server"> <div> <as ...

  9. upload控件上传json文件合并的两种方法

    方法一: byte[] byte1 = FileUpload1.FileBytes; byte[] byte2 = FileUpload2.FileBytes; byte[] a1 = Encodin ...

随机推荐

  1. Runtime - 01

    Runtime是想要做好iOS开发,或者说是真正的深刻的掌握OC这门语言所必需理解的东西.最近在学习Runtime,有自己的一些心得,整理如下, 什么是Runtime 我们写的代码在程序运行过程中都会 ...

  2. 安全测试常见的10个问题 ZT

    1, 问题:没有被验证的输入     测试方法:     数据类型(字符串,整型,实数,等)    允许的字符集    最小和最大的长度    是否允许空输入    参数是否是必须的    重复是否允 ...

  3. Vases and Flowers

    hdu4614:http://acm.hdu.edu.cn/showproblem.php?pid=4614 题意:给你n个花瓶,然后有两种操作:1从a开始选择b个花瓶,放进花,输出左端点,右端点 2 ...

  4. php获取请求的方式(get/post)

    $request_method = $_SERVER['REQUEST_METHOD'];//用什么方式访问 get post

  5. 轻松使用Nginx搭建web服务器

    如果读者以前做过web开发的话,就应该知道如何去搭建一个web服务器来跑你的web站点,在windows下你可能会选择去用IIS,十分的快捷,在linux下,你可能首先会想到apache,“一哥”( ...

  6. 第八章CDC设备

    8.1 CDC设备介绍 USB的CDC类是USB通信设备类(Communication Device Class)的简称.CDC类是USB组织定义的一类专门给各种通信设备(电信通信设备和中速网络通信设 ...

  7. (转载)NET流操作

    http://www.oseye.net/user/kevin/blog/86 概念 数据流(Stream)是对串行传输数据的一种抽象表示,是对输入/输出的一种抽象.数据有来源和目的地,衔接两者的就是 ...

  8. 启动Activity时显示空白界面的问题

    问题描述: 启动activity时,先显示一个空白的界面,带标题栏的,1秒左右的时间后才显示activity对应 layout上的内容. 解决办法: 将activity的windows设置为透明的就可 ...

  9. 【HDOJ】4516 威威猫系列故事——因式分解

    可解的算法太多了,采用的算法是试x的值.注意题目的输入x^3-2x^2不会写成x^3+-2x^2.一直RE在这儿. /* 4516 */ #include <iostream> #incl ...

  10. MS-DOS 7.10完整安装版(含图文安装程序)

    大家知道,要想学习或使用DOS,安装一个DOS并进行实际操作是非常必要的.MS-DOS 7.10是一个非常好且强大实用的操作系统,而且兼容性和性能都十分强.要在系统中安装MS-DOS 7.10,可以使 ...