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

Convert file received from jquery to byte array

本文关键字:字节 字节数 数组 转换 文件 jquery 将从      更新时间:2023-09-26

我需要帮助将从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调用中检索文件后,是否有其他方法可以将文件转换为字节数组?

这些文章的署名:

  • 使用ASP.NET从SQL Server数据库中保存和检索文件
  • 使用jQuery和ASP.NET异步上传文件

只需这3行即可:

    int filelength = file.ContentLength;
    byte[] imagebytes = new byte[filelength ];
    file.InputStream.Read(imagebytes , 0, filelength );
using (var stream = upload.InputStream)
{
    // use stream here: using StreamReader, StreamWriter, etc.
}