2012-07-10 38 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. 
} 
相关问题