2012-07-10 33 views
0

我需要幫助將從jquery ajax接收到的文件轉換爲字節數組。我正在使用一個名爲ajaxfileupload的插件,然後從jquery ajax調用我發送文件從文件上傳控件到處理程序。這裏是我的 處理代碼:將從jquery接收到的文件轉換爲字節數組

if (context.Request.Files.Count > 0) 
{ 
    string path = context.Server.MapPath("~/Temp"); 
    if (!Directory.Exists(path)) 
     Directory.CreateDirectory(path); 

    var file = context.Request.Files[0]; 

    string fileName; 

    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") 
    { 
     string[] files = file.FileName.Split(new char[] { '\\' }); 
     fileName = files[files.Length - 1]; 
    } 
    else 
    { 
     fileName = file.FileName; 
    } 
    string fileType = file.ContentType; 
    string strFileName = fileName; 

    FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read); 
    BinaryReader br = new BinaryReader(fs); 
    Byte[] imagebytes = br.ReadBytes((Int32)fs.Length); 
    br.Close(); 
    fs.Close(); 

    DBAccess dbacc = new DBAccess(); 
    dbacc.saveImage(imagebytes); 

    string msg = "{"; 
    msg += string.Format("error:'{0}',\n", string.Empty); 
    msg += string.Format("msg:'{0}'\n", strFileName); 
    msg += "}"; 
    context.Response.Write(msg); 
} 

我將文件保存到一個文件夾一個項目中,然後嘗試檢索文件並將其保存到數據庫中。我可以向你保證圖像正被保存到臨時文件夾。問題在於(*)文件路徑錯誤。這是正在檢索的文件路徑。 「'C:\ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \〜\ Temp \ 2012-06-03 01.25.47.jpg'。」。臨時文件夾位於我的項目本地,我想要檢索該文件夾內的圖像。如何將文件路徑設置到我想要的位置?或者有另一種方法來從jquery ajax調用中獲取它後將文件轉換爲字節數組?

積分這些文章:

+0

考慮這篇文章:[未激發的樣子瀏覽器嗅探](http://balpha.de/2012/07/an-unexcited-look-at-browser-sniffing/) – abatishchev 2012-07-10 15:13:20

回答

1

就這3個行會做:

int filelength = file.ContentLength; 
    byte[] imagebytes = new byte[filelength ]; 
    file.InputStream.Read(imagebytes , 0, filelength); 
+0

哇!我不敢相信這可能會很容易。我讀過的所有文章都是特定於文件路徑的。我想我應該試試更多。謝謝! – ljpv14 2012-07-10 15:12:03

+0

@ SSA-先生再次感謝您的幫助。但圖像不顯示。有一個破碎的圖像標誌,我認爲這是轉換失敗或類型問題。你能幫助我嗎? – ljpv14 2012-07-11 09:41:03

+0

我認爲它與將輸入流轉換爲字節數組無關。你可以驗證字節數組有數據和文件長度是否正確? – SSA 2012-07-11 09:45:58

-3
using (var stream = upload.InputStream) 
{ 
    // use stream here: using StreamReader, StreamWriter, etc. 
} 
相關問題