javascript 将从 jquery 接收的文件转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11415809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert file received from jquery to byte array
提问by Luke Villanueva
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:
我需要帮助将从 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);
}
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?
我将文件保存到项目内的文件夹中,然后尝试检索该文件并将其保存到数据库中。我可以向您保证,图像正在保存到临时文件夹中。问题在于带有 (*) 的行文件路径错误。这是正在检索的文件路径。“'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.”。临时文件夹位于我的项目本地,我想检索该文件夹中的图像。如何将文件路径设置为我想要的位置?或者在从 jquery ajax 调用中检索文件后是否有另一种方法将文件转换为字节数组?
Credits to these articles:
这些文章的学分:
回答by SSA
Just these 3 lines will do:
只需这 3 行即可:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );
回答by abatishchev
using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}