C#最齐全的上传图片方法介绍


本文摘自PHP中文网,作者黄舟,侵删。

本文主要介绍了C# 最齐全的上传图片方法,方法里包括了图片大小限制、图片尺寸、文件内容等等的判断。具有很好的参考价值,下面跟着小编一起来看下吧

方法里包括了图片大小限制、图片尺寸、文件内容等等的判断。。。

该案例是mvc下的demo,支持单张图片上传。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

public ActionResult Upload()

    {

      string imgurl = "";

      foreach (string key in Request.Files)

      {

        //这里只测试上传第一张图片file[0]

        HttpPostedFileBase file0 = Request.Files[key];

        //转换成byte,读取图片MIME类型

        Stream stream;

        int size = file0.ContentLength / 1024; //文件大小KB

        if (size > 1024)

        {

          return Content(ReturnMsg(Enum_Return.失败, "图片不能超过1M:", null));

        }

        byte[] fileByte = new byte[2];//contentLength,这里我们只读取文件长度的前两位用于判断就好了,这样速度比较快,剩下的也用不到。

        stream = file0.InputStream;

       stream.Read(fileByte, 0, 2);//contentLength,还是取前两位

        //获取图片宽和高

        //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

        //int width = image.Width;

        //int height = image.Height;

        string fileFlag = "";

        if (fileByte != null && fileByte.Length > 0)//图片数据是否为空

        {

          fileFlag = fileByte[0].ToString()  fileByte[1].ToString();

        }

        string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png

        if (fileTypeStr.Contains(fileFlag))

        {

          string action = Request["action"];

          string path = "/uploads/";

          switch (action)

          {

            case "headimage":

              path  = "headimage/";

              break;

            case "blogtype":

              path  = "blogtype/";

              break;

          }

          string fullpath = path  UserInfo.userID  "/";

          if (!Directory.Exists(Server.MapPath(fullpath)))

          {

            Directory.CreateDirectory(Server.MapPath(fullpath));

          }

          Request.Files[key].SaveAs(Server.MapPath(fullpath  Request.Files[key].FileName));

          imgurl = fullpath  Request.Files[key].FileName;

        }

        else

        {

          return Content(ReturnMsg(Enum_Return.失败, "图片格式不正确:" fileFlag, null));

        }

        stream.Close();

      }

      return Content(ReturnMsg(Enum_Return.成功, "上传成功", imgurl));

    }

一般处理程序

阅读剩余部分

相关阅读 >>

C#开发实例-订制屏幕截图工具(九)使用自定义光标和qq截图时的光标(图)

关于C#中三个关键字params,ref,out的详细介绍

C#泛型类型的详细介绍

C#因其保护级别而不可访问,只能处理公共类型的详细代码介绍

C#中的数据类型是什么?C#中的四种数据类型解释

C#中winform制作异形窗体与控件的实现方法

C#中default什么意思

C#如何利用reportviewer来生成报表的示例代码分享(图)

C#高级编程(三)-对象和类型详解

C#二进制字节数组操作函数 截取字节数组subbyte的示例代码

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...