您的位置:首页 > 其它

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

2016-02-25 11:42 239 查看
一般开发都是使用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); //只需要写入读取到的字节数就可以了
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: