使用MVC3做服务器端的处理时遇到的一大问题是HttpPostedFileBase为null,request.file也为null,这是上面的博客中没有提到的(PHP),一番潜心研究中,发现了Request.InputStream中有数据,于是乎:
[HttpPost]
public JsonResult FileUpload()
{
Stream RequestStream =HttpContext.Request.InputStream;//把文件的数据读取到st流中
if (RequestStream == null)
{
return Json(new { msg=0,msgbox="上传的文件为空"});//"上传的文件为空";
}
string file_name = HttpContext.Request.Headers["X_FILENAME"].ToString();
if(string.IsNullOrWhiteSpace(file_name))
{
return Json(new { msg = 0, msgbox = "文件名为空" });//"文件名为空";
}
int last_Index = file_name.LastIndexOf(".");
string fileExt = file_name.Substring(last_Index+1,file_name.Length -last_Index -1); //得到文件的拓展名,不包含“.”
string saveFloder = Server.MapPath("/uploads/"); //保存的文件路径
if (!Directory.Exists(saveFloder)) //如果该文件夹不存在, 则创建
{
Directory.CreateDirectory(saveFloder);
}
string save_name = Guid.NewGuid().ToString()+"."+fileExt; //保存的文件名
////创建一个文件流来把上传的文件写入到服务器上
FileStream fs = new FileStream(saveFloder + save_name, FileMode.Create, FileAccess.Write, FileShare.Read);
byte[] buffer = new byte[1024];//缓冲区
int readLen;//每次真正读取到的字节数
while ((readLen = RequestStream.Read(buffer, 0, 1024)) > 0)
{
//读到数据了(此时独到的数据在buffer缓冲区中)
//开始把文件写入到服务器的磁盘中
fs.Write(buffer, 0, readLen);
}
fs.Flush();//请空缓冲区,使得所有缓冲区的数据都写入到文件中
RequestStream.Flush();
fs.Close();//关闭流,释放资源
RequestStream.Close();
return Json(new { msg = 1, msgbox = "/uploads/" + save_name });
}