[英]Unable to convert file in byte array
當我嘗試使用此代碼將文件轉換為字節數組時,我有一個問題
var fileByte = new byte[pic.ContentLength];
它會轉換文件,但是當文件上傳時它會被破壞。 當我嘗試另一個代碼來轉換文件,即
var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
byte[] bytes = System.IO.File.ReadAllBytes(pic.FileName);
它拋出了一個例外
找不到文件'C:\\ Program Files \\ IIS Express \\ slide2.jpg'。
在我試過這個詞之后
byte[] b = StreamFile(pic.FileName);
private byte[] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData; //return the byte data
}
但它也拋出和異常一樣
找不到文件'C:\\ Program Files \\ IIS Express \\ slide2.jpg'。
第一行代碼不會將文件轉換為字節數組,它只是創建一個大小為pic.ContentLength
的字節數組。
第二個示例拋出一個異常,該異常清楚地表明您沒有指定路徑上的圖像(由pic.FileName
定義)。
要解決此問題,您應該使用請求的文件Stream
並將其寫入字節數組。
var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
byte[] bytes;
using (var stream = new MemoryStream())
{
pic.InputStream.CopyTo(stream);
bytes = stream.ToArray();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.