该案例是mvc下的demo,支持单张图片上传。
1 public ActionResult Upload()
2 {
3 string imgurl = "";
4 foreach (string key in Request.Files)
5 {
6 //这里只测试上传第一张图片file[0]
7 HttpPostedFileBase file0 = Request.Files[key];
8
9 //转换成byte,读取图片MIME类型
10 Stream stream;
11 int size = file0.ContentLength / 1024; //文件大小KB
12
13 if (size > 1024)
14 {
15 return Content(ReturnMsg(Enum_Return.失败, "图片不能超过1M:", null));
16 }
17
18 byte[] fileByte = new byte[2];//contentLength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。
19 stream = file0.InputStream;
20 stream.Read(fileByte, 0, 2);//contentLength,还是取前两位
21
22 //获取图片宽和高
23 //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
24 //int width = image.Width;
25 //int height = image.Height;
26
27
28 string fileFlag = "";
29 if (fileByte != null && fileByte.Length > 0)//图片数据是否为空
30 {
31 fileFlag = fileByte[0].ToString() fileByte[1].ToString();
32 }
33 string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png
34 if (fileTypeStr.Contains(fileFlag))
35 {
36 string action = Request["action"];
37 string path = "/uploads/";
38 switch (action)
39 {
40 case "headimage":
41 path = "headimage/";
42 break;
43 case "blogtype":
44 path = "blogtype/";
45 break;
46 }
47 string fullpath = path UserInfo.userID "/";
48 if (!Directory.Exists(Server.MapPath(fullpath)))
49 {
50 Directory.CreateDirectory(Server.MapPath(fullpath));
51 }
52
53
54 Request.Files[key].SaveAs(Server.MapPath(fullpath Request.Files[key].FileName));
55 imgurl = fullpath Request.Files[key].FileName;
56 }
57 else
58 {
59 return Content(ReturnMsg(Enum_Return.失败, "图片格式不正确:" fileFlag, null));
60 }
61
62 stream.Close();
63 }
64
65 return Content(ReturnMsg(Enum_Return.成功, "上传成功", imgurl));
66 }
一般处理程序
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
HttpPostedFile _upfile = context.Request.Files["File"];
if (_upfile.ContentLength < 500000)
{
if (string.IsNullOrEmpty(_upfile.FileName))
{
context.Response.Write("请上传图片");
}
string fileFullname = _upfile.FileName;
string dataName = DateTime.Now.ToString("yyyyMMddhhmmss");
string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\") 1);
string type = fileFullname.Substring(fileFullname.LastIndexOf(".") 1);
if (type == "bmp" || type == "jpg" || type == "gif" || type == "JPG" || type == "BMP" || type == "GIF")
{
_upfile.SaveAs(HttpContext.Current.Server.MapPath("photo") "\" dataName "." type);
HttpCookie cookie = new HttpCookie("photo");
context.Response.Write("上传成功");
}
else
{
context.Response.Write("支持格式:|jpg|gif|bmp|");
}
}
else
{
context.Response.Write("你的图片已经超过500K的大小!");
}
}