一般開發都是使用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[];
//當沒有讀取到檔案的末尾的時候就需要循環讀取
while (fsRead.Position < fsRead.Length)
{//讀取的時候position屬性會自動變化,記住目前讀取到的位置,以位元組為機關
//count可以擷取目前具體讀取到的位元組數
int count = fsRead.Read(bytes, , bytes.Length);
if (count == ){ break; }
//寫入
fsWrite.Write(bytes, , count); //隻需要寫入讀取到的位元組數就可以了
}
}
}