The most complete method of uploading pictures in C

  • 2021-11-29 08:14:40
  • OfStack

The method includes the judgment of picture size limit, picture size, file content and so on. . .

This case is demo under mvc, which supports uploading a single picture.


public ActionResult Upload()
    {
      string imgurl = "";
      foreach (string key in Request.Files)
      {
        // Here only test the upload 1 A picture file[0]
        HttpPostedFileBase file0 = Request.Files[key];
        // Convert to byte, Read a picture MIME Type 
        Stream stream;
        int size = file0.ContentLength / 1024; // File size KB
        if (size > 1024)
        {
          return Content(ReturnMsg(Enum_Return. Failure , " Pictures cannot exceed 1M : ", null));
        }
        byte[] fileByte = new byte[2];//contentLength Here, we only read the first two bits of the file length for judgment, so the speed is faster, and the rest is not used. 
        stream = file0.InputStream;
       stream.Read(fileByte, 0, 2);//contentLength Or take the top two 
        // Get the width and height of the picture 
        //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)// Whether the picture data is empty 
        {
          fileFlag = fileByte[0].ToString()  fileByte[1].ToString();
        }
        string[] fileTypeStr = { "255216", "7173", "6677", "13780" };// Corresponding picture format 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. Failure , " Image format is incorrect: " fileFlag, null));
        }
        stream.Close();
      }
      return Content(ReturnMsg(Enum_Return. Success , " Upload succeeded ", imgurl));
    }

1 general handler


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(" Please upload pictures ");
      }
      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(" Upload succeeded ");
      }
      else
      {
        context.Response.Write(" Supported formats: |jpg|gif|bmp|");
      }
    }
    else
    {
      context.Response.Write(" Your picture has exceeded 500K The size of! ");
    }
  }

Related articles: