c#上传文件(二)使用文件流保存文件

1.html代码:

<asp:FileUpload runat="server" ID="UpLoadFile"/> 
        <asp:Button runat="server" ID="btnUpLoad" OnClick="btnUpLoad_Click" Text="上传"/>
html代码

2.后台代码:

public partial class UpLoadFilesByStream : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        { }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            //对于文件的格式和大小的判断,在上一篇已经涉及,这里省略。
            if (this.UpLoadFile.HasFile)
            {
                //HttpPostedFile类提供对客户端已上载的单独文件的访问
                HttpPostedFile hpf = this.UpLoadFile.PostedFile;
                //HttpPostedFile hpf = Request.Files[0];
                //文件名
                string fileName = Path.GetFileName(hpf.FileName);
                //文件大小,单位字节
                int fileContentLength = hpf.ContentLength;
                //上传路径
                string filePath = Server.MapPath("/Files/");
                //二进制数组
                byte[] fileBytes = null;
                fileBytes = new byte[fileContentLength];
                //创建Stream对象,并指向上传文件
                Stream fileStream = hpf.InputStream;
                //从当前流中读取字节,读入字节数组中
                fileStream.Read(fileBytes, 0, fileContentLength);
                //全路径(路劲+文件名)
                string fullPath = filePath + fileName;
                //保存到磁盘
                SaveToDisk(fileBytes, fullPath);
            }
        }

        /// <summary>
        /// 保存到磁盘
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <param name="saveFullPath">全路径</param>
        /// <returns></returns>
        public void SaveToDisk(byte[] bytes, string saveFullPath)
        {
            var fullPath = Path.GetDirectoryName(saveFullPath);
            //如果没有此文件夹,则新建
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
            //创建文件,返回一个 FileStream,它提供对 path 中指定的文件的读/写访问。
            using (FileStream stream = File.Create(saveFullPath))
            {
                //将字节数组写入流
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }
        }
    }
.cs代码

测试通过!

原文地址:https://www.cnblogs.com/qk2014/p/4620614.html