使用byte[]進行檔案上傳
1.背景
需要以byte[]資料流的方式傳輸檔案到伺服器,並在伺服器還原檔案。
2.程式碼
(1)轉換為byte[]
# region function1
FileStream fs = File.OpenRead(@"D:\\workspace\test.txt");
MemoryStream tempStream = new System.IO.MemoryStream();
int bi;
while ((bi = fs.ReadByte()) != -1)
{
tempStream.WriteByte(((byte)bi));
}
byte[] buffer = tempStream.ToArray();
string ss = JsonConvert.SerializeObject(buffer);
# endregion
#region function2
FileStream stream = new FileInfo(@"D:\\workspace\test.txt").OpenRead();
Byte[] buffer = new Byte[stream.Length];
//從流中讀取位元組塊並將該資料寫入給定緩衝區buffer中
stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
return buffer;
#endregion
(2)從byte[]轉換為檔案,並儲存在給定位置
FileStream fileStream = null;
MemoryStream ms = new MemoryStream(buffer);
try
{
string savePath = "lujing";
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
fileStream = new FileStream(savePath + fileName, FileMode.Create);
ms.WriteTo(fileStream);
}
catch (Exception ex){
throw ex;
}
finally
{
ms.Close();
fileStream.Close();
}
3.超過4m檔案上傳
<system.web>
<httpRuntime maxRequestLength= "51200" executionTimeout="3600" targetFramework="4.5" />
<system.web>