通過.NET上傳圖象

來源:互聯網
上載者:User
上傳

以前,通過ASP上傳圖象(圖象的大小、類型都受到限制)一般都是要藉助外部組件來完成,.NET的出現,使這一工作變得非常容易並且可以隨便的使用Bitmap和Image類型。

在這個指導思想下,我將按照以下步驟(在你要上傳圖象檔案上)建立一個簡單的WEB表單,該表單將判斷上傳的檔案是否是JPEG檔案、判斷該檔案是否存在(必要時你可以重新命名)。

1、  建立一個新Web 應用程式項目;

2、  開啟Web Form;

3、  在表單上面添加一個HTML表單,並把它轉換成伺服器控制項。在這個例子裡,該檔案將命名為filUpload;(把HTML轉換成伺服器控制項的方法是,在它的上面右擊滑鼠然後選擇Run As Server Control)

4、  切換到HTML view並添加/更改FORM標籤的enctype屬性為multipart/form-data。如:enctype="multipart/form-data"。

5、  在Web表單上添加一個BUTTON並命名為btnUpload。

6、  向Web應用程式添加一個folder called /images。

7、  在表單上添加一個Web Form Image並命名為imgPicture,設定寬度和高度分別為160和120。

8、  添加一個Label控制項並命名為lblOutput。顯示當在上傳的過程中發生的任何錯誤。

9、  給按鈕btnUpload的單擊事件添加如下代碼:(如果你想分析以下代碼的細節,你可以把下面的代碼複製粘貼到VS.NET IDE整合式開發環境。)

1.     private void btnUpload_Click(object sender, System.EventArgs e)
2.     {
3.         // Initialize variables
4.         string sSavePath;
5.         string sThumbExtension;
6.         int intThumbWidth;
7.         int intThumbHeight;
8.     
9.         // Set constant values
10.      sSavePath = "images/";
11.      sThumbExtension = "_thumb";
12.      intThumbWidth = 160;
13.      intThumbHeight = 120;
14.  
15.      // If file field isn’t empty
16.      if (filUpload.PostedFile != null)
17.      {
18.          // Check file size (mustn’t be 0)
19.          HttpPostedFile myFile = filUpload.PostedFile;
20.          int nFileLen = myFile.ContentLength;
21.          if (nFileLen == 0)
22.          {
23.              lblOutput.Text = "No file was uploaded.";
24.              return;
25.          }
26.  
27.          // Check file extension (must be JPG)
28.          if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
29.          {
30.              lblOutput.Text = "The file must have an extension of JPG";
31.              return;
32.          }
33.  
34.          // Read file into a data stream
35.          byte[] myData = new Byte[nFileLen];
36.          myFile.InputStream.Read(myData,0,nFileLen);
37.  
38.          // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an
39.          // incremental numeric until it is unique
40.          string sFilename = System.IO.Path.GetFileName(myFile.FileName);
41.          int file_append = 0;
42.          while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
43.          {
44.              file_append++;
45.              sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
46.                               + file_append.ToString() + ".jpg";
47.          }
48.  
49.          // Save the stream to disk
50.          System.IO.FileStream newFile
51.                  = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
52.                                             System.IO.FileMode.Create);
53.          newFile.Write(myData,0, myData.Length);
54.          newFile.Close();
55.  
56.          // Check whether the file is really a JPEG by opening it
57.          System.Drawing.Image.GetThumbnailImageAbort myCallBack =
58.                         new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
59.          Bitmap myBitmap;
60.          try
61.          {
62.              myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
63.  
64.              // If jpg file is a jpeg, create a thumbnail filename that is unique.
65.              file_append = 0;
66.              string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
67.                                                       + sThumbExtension + ".jpg";
68.              while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
69.              {
70.                  file_append++;
71.                  sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
72.                                 file_append.ToString() + sThumbExtension + ".jpg";
73.              }
74.  
75.              // Save thumbnail and output it onto the webpage
76.              System.Drawing.Image myThumbnail
77.                      = myBitmap.GetThumbnailImage(intThumbWidth,
78.                                                   intThumbHeight, myCallBack, IntPtr.Zero);
79.              myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
80.              imgPicture.ImageUrl = sSavePath + sThumbFile;
81.  
82.              // Displaying success information
83.              lblOutput.Text = "File uploaded successfully!";
84.  
85.              // Destroy objects
86.              myThumbnail.Dispose();
87.              myBitmap.Dispose();
88.          }
89.          catch (ArgumentException errArgument)
90.          {
91.              // The file wasn't a valid jpg file
92.              lblOutput.Text = "The file wasn't a valid jpg file.";
93.              System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
94.          }
95.      }
96.  }
97.  
98.  public bool ThumbnailCallback()
99.  {
100.         return false;
}     

10.運行以上建立的 Web頁(webpage),並分別使用JPG檔案和其他類型的檔案來測試錯誤檢查(error-checking)機制。

11. 如果你有什麼問題或建議,請給作者留言。

-------------------------------------------------------------

關於Chris Khoo

I was born in Malaysia on 13th February 1982 and moved to Australia when I was 8. I also started programming around that time as well in GWBasic . Over the years, I picked up Assembly, Pascal, and C/C++.

In my teen/adult years when Windows programming became the norm, I also learnt some MFC, Visual Basic, and Java and have completed some web projects utilizing ASP and also created Office VBA macros for businesses.

Within this time, I picked up a MCSD and MCSE, however I finally chose to go to university instead of working a full time software development job.

Currently, at age 20, I am studying Commerce(Accounting) and Information Technology at the University of Queensland, and it is a blast.

I enjoy working with businesses to help grow them in whatever way (usually it involves IT initially), challenging software/web development projects and learning new things everyday. (I'm into this .NET stuff now).



相關文章

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。