csharp: Gets a files formatted size.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
          ASP.NET 默认上传文件是4M ,可以修改服务配置..
 
         <system.web>
         <!-- 指示 ASP.NET 支持的最大文件上载大小。
         该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。
         指定的大小以 KB 为单位。默认值为 4096 KB (4 MB)。最大为:2097151 KB
         此处改为40M大小的文件上传限制。
         -->
         <httpRuntime maxRequestLength = "2097151" useFullyQualifiedRedirectUrl="true"/>
         </system.web>
          */
 
      /// <summary>
      /// Gets a files formatted size.
      /// </summary>
      /// <param name="file">The file to return size of.</param>
      /// <returns></returns>
      //public static string GetFileSize(this FileInfo file)
      //{
      //    try
      //    {
      //        //determine all file sizes
      //        double sizeinbytes = file.Length;
      //        double sizeinkbytes = Math.Round((sizeinbytes / 1024));
      //        double sizeinmbytes = Math.Round((sizeinkbytes / 1024));
      //        double sizeingbytes = Math.Round((sizeinmbytes / 1024));
      //        if (sizeingbytes > 1)
      //            return string.Format("{0} GB", sizeingbytes); //returns size in gigabytes
      //        else if (sizeinmbytes > 1)
      //            return string.Format("{0} MB", sizeinmbytes); //returns size in megabytes if less than one gigabyte
      //        else if (sizeinkbytes > 1)
      //            return string.Format("{0} KB", sizeinkbytes); //returns size in kilabytes if less than one megabyte
      //        else
      //            return string.Format("{0} B", sizeinbytes); //returns size in bytes if less than one kilabyte
      //    }
      //    catch { return "Error Getting Size"; } //catches any possible error and just returns error getting size
      //}
 
      /// <summary>
      /// Gets a files formatted size.
      /// 获得文件大小
      /// 涂聚文
      ///
      /// Geovin Du
      /// </summary>
      /// <param name="file"></param>
      /// <returns></returns>
      public string GetFileSize(double file)
      {
          try
          {
              //1.
              double byteSize = Math.Round(file / 1024 * 100) * 0.01;
              string suffix = "KB";
              if (byteSize > 1000)
              {
                  byteSize = Math.Round(byteSize * .001 * 100) * .01;
                  suffix = "MB";
              }
              double byteGSize = Math.Round(byteSize / 1024 * 100) * 0.01;
              if (byteGSize > 1000)
              {
                  byteGSize = Math.Round(byteGSize * .001 * 100) * .01;
                  suffix = "GB";
              }
              return byteSize.ToString() + suffix;
 
              //2.
              //determine all file sizes
              //double sizeinbytes = file;
              //double sizeinkbytes = Math.Round((sizeinbytes / 1024));
              //double sizeinmbytes = Math.Round((sizeinkbytes / 1024));
              //double sizeingbytes = Math.Round((sizeinmbytes / 1024));
              //if (sizeingbytes > 1)
              //    return string.Format("{0:0.00} GB", sizeingbytes); //returns size in gigabytes
              //else if (sizeinmbytes > 1)
              //    return string.Format("{0:0.00} MB", sizeinmbytes); //returns size in megabytes if less than one gigabyte
              //else if (sizeinkbytes > 1)
              //    return string.Format("{0:0.00} KB", sizeinkbytes); //returns size in kilabytes if less than one megabyte
              //else
              //    return string.Format("{0} B", sizeinbytes); //returns size in bytes if less than one kilabyte
          }
          catch
          {
              return "Error Getting Size";
          } //catches any possible error and just returns error getting size
      }

  

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
57
58
59
60
61
62
63
64
65
66
67
68
/// <summary>
      ///
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      protected void Button1_Click(object sender, EventArgs e)
      {
          int FileNum = 0;
          // Clear the BulletedList.
          BulletedList1.Items.Clear();
          string filepath = Server.MapPath("./") + "UploadFile";
          string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
          HttpFileCollection hfc = Request.Files;
          //1
          for (int i = 0; i < hfc.Count; i++)
          {
              HttpPostedFile hpf = hfc[i];
              if (hfc[i].ContentLength > 0)
              {
                  hpf.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
                  FileNum++;
                  //uploadFiles.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
                  FileUpload1.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
                  FileUpload2.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
              }
              else
              {
                  Response.Write("<script>alert('请选择你要上传的文件!')</script>");
                  //跳出for循环
                  i = hfc.Count;
                  break;
              }
          }
          Response.Write("<script>alert('上传成功!')</script>");
          Response.Write("共上传成功的文件个数为:" + FileNum + "个");
          FileNum = 0;
 
          // Check to see if at least one file was specified.
          //if (FileUpload1.HasFile | FileUpload2.HasFile)
          //{
          //    Label1.Text = "The file collection consists of:";
 
          //    // Get the HttpFileCollection.
          //    //HttpFileCollection hfc = Request.Files;
          //    foreach (String h in hfc.AllKeys)
          //    {
          //        // Add an item to the BulletedList if a file
          //        // was specified for the corresponding control.
          //        if (hfc[h].ContentLength > 0)
          //        {  
          //            BulletedList1.Items.Add(Server.HtmlEncode(hfc[h].FileName));
          //        }
 
 
          //    }
          //    for (int i = 0; i < hfc.Count; i++)
          //    {
          //        filename = DateTime.Now.ToString("yyyyMMddHHmmss");
          //        HttpPostedFile hpf = hfc[i];
          //        hpf.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
          //    }
          //}
          //else
          //{
          //    Label1.Text = "You did not specify any files to upload or "+ hfc.Count.ToString()+
          //        "the file(s) could not be found.";
          //}
      }

  

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    this.AddFile.Click += new System.EventHandler(this.AddFile_Click);
    this.RemvFile.Click += new System.EventHandler(this.RemvFile_Click);
    this.Upload.ServerClick += new System.EventHandler(this.Upload_ServerClick);
}
 
 
/// <summary>
/// AddFile will add the path of the client side file that is currently in the PostedFile
/// property of the HttpInputFile control to the listbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddFile_Click(object sender, System.EventArgs e)
{
    if (Page.IsPostBack == true)
    {
        hif.Add(FindFile);
        double size = FindFile.PostedFile.ContentLength;
        string filesize = GetFileSize(size);
        ListBox1.Items.Add(FindFile.PostedFile.FileName + "  文件大小:" + filesize);
       // FindFile.PostedFile.ContentLength.ToString();
    }
    else
    {
 
    }
}
 
/// <summary>
/// RemvFile will remove the currently selected file from the listbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RemvFile_Click(object sender, System.EventArgs e)
{
    if (ListBox1.Items.Count != 0)
    {
 
        hif.RemoveAt(ListBox1.SelectedIndex);
        ListBox1.Items.Remove(ListBox1.SelectedItem.Text);
    }
 
}
 
/// <summary>
/// Upload_ServerClick is the server side script that will upload the files to the web server
/// by looping through the files in the listbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Upload_ServerClick(object sender, System.EventArgs e)
{
    string baseLocation = Server.MapPath("/upload/");
    string status = "";
 
 
    if ((ListBox1.Items.Count == 0) && (filesUploaded == 0))
    {
        Label1.Text = "Error - a file name must be specified.";
        return;
 
    }
    else
    {
        foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
        {
            try
            {
                string fn = System.IO.Path.GetFileName(HIF.PostedFile.FileName);
                HIF.PostedFile.SaveAs(baseLocation + fn);
                filesUploaded++;
                status += fn + "<br>";
            }
            catch (Exception err)
            {
                Label1.Text = "Error saving file " + baseLocation + "<br>" + err.ToString();
            }
        }
 
        if (filesUploaded == hif.Count)
        {
            Label1.Text = "These " + filesUploaded + " file(s) were uploaded:<br>" + status;
        }
        hif.Clear();
        ListBox1.Items.Clear();
    }
 
}

  

posted @   ®Geovin Du Dream Park™  阅读(363)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2013-04-20 SVG In HTML5 Pages
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示