0

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:

4

2 回答 2

1

只需这 3 行即可:

    int filelength = file.ContentLength;
    byte[] imagebytes = new byte[filelength ];
    file.InputStream.Read(imagebytes , 0, filelength );
于 2012-07-10T15:02:44.853 回答
-3
using (var stream = upload.InputStream)
{
    // use stream here: using StreamReader, StreamWriter, etc.
}
于 2012-07-10T15:07:07.923 回答