简体   繁体   English

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

[英]Convert file received from jquery to byte array

I need help in converting a file received from a jquery ajax to byte array. 我需要帮助将从jquery ajax接收的文件转换为字节数组。 I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. 我正在使用一个名为ajaxfileupload的插件,然后从jquery ajax调用中,我将文件从fileupload控件发送到处理程序。 Here is my handler code: 这是我的处理程序代码:

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);
}

I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. 我将文件保存到项目内的文件夹中,然后尝试检索该文件并将其保存到数据库中。 I can assure you that the image is being saved to the temp folder. 我可以向您保证图像已保存到temp文件夹中。 The problem is with the line with (*) the file path is wrong. 问题在于带有(*)的行文件路径错误。 This is the file path that is being retrieved. 这是正在检索的文件路径。 "'C:\\Program Files\\Common Files\\Microsoft Shared\\DevServer\\10.0\\~\\Temp\\2012-06-03 01.25.47.jpg'.". “'C:\\ Program Files \\ Common Files \\ Microsoft Shared \\ DevServer \\ 10.0 \\〜\\ Temp \\ 2012-06-03 01.25.47.jpg'。” The temp folder is located locally inside my project and I want to retrieved the image within that folder. 临时文件夹位于我的项目内部,我想在该文件夹中检索图像。 How can I set the file path to my desired location? 如何将文件路径设置到所需位置? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call? 还是从jquery ajax调用检索文件后将文件转换为字节数组的另一种方法?

Credits to these articles: 归功于这些文章:

Just these 3 lines will do: 仅以下三行即可:

    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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM