根据客户端文件路径及服务器保存路径上传文件

来源:互联网 发布:魔法王座 知乎 编辑:程序博客网 时间:2024/05/17 20:38

一般开发都是使用file控件等进行文件上传,今天在开发中遇到js传递包含文件路径的json字符串,于是想在服务器端根据路径进行文件上传,采用流上传。
主要代码为:

 string filepath = '' //文件上传本地地址; FileInfo fs = new FileInfo(filepath); string fileName = fs.Name;  //获取文件名 string dir = HttpContext.Current.Server.MapPath("../template/" + fileName); //保存在服务器上的路径 using (FileStream fsRead = new FileStream(filepath, FileMode.Open)) {   using (FileStream fsWrite = new FileStream(dir, FileMode.Create))     {//自定义数组的长度        byte[] bytes = new byte[1024];        //当没有读取到文件的末尾的时候就需要循环读取        while (fsRead.Position < fsRead.Length)        {//读取的时候position属性会自动变化,记住当前读取到的位置,以字节为单位          //count可以获取当前具体读取到的字节数          int count = fsRead.Read(bytes, 0, bytes.Length);          if (count == 0){ break; }           //写入           fsWrite.Write(bytes, 0, count); //只需要写入读取到的字节数就可以了        }       }   }
0 0