简体   繁体   中英

Convert file received from jquery to byte array

I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. 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. 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'.". 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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