将从jquery接收的文件转换为字节数组

时间:2012-07-10 14:41:06

标签: c# javascript jquery asp.net file-upload

我需要帮助将从jquery ajax接收的文件转换为字节数组。我正在使用一个名为ajaxfileupload的插件然后从jquery ajax调用我将文件从fileupload控件发送到处理程序。这是我的 处理程序代码:

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调用中检索后转换为字节数组?

对这些文章的信任:

2 个答案:

答案 0 :(得分:1)

这3行就可以了:

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

答案 1 :(得分:-3)

using (var stream = upload.InputStream)
{
    // use stream here: using StreamReader, StreamWriter, etc.
}
相关问题