.NET 图片上传






4.65/5 (55投票s)
2002 年 3 月 13 日
2分钟阅读

829393

11164
在 .NET 中上传图片,以及生成缩略图、调整大小等。
通过 .NET 上传图片
以前,要在 ASP 中添加上传图片的功能(包括调整大小、缩略图功能等),需要使用外部组件。 随着 .NET 的出现,可以使用 Bitmap 和 Image 类轻松且免费地处理图像。在本教程中,我们将逐步创建一个简单的 Web 表单,您可以在其中上传图像文件,表单将验证它是否为 JPEG 文件,是否已经存在重复文件(如果需要,重命名上传的文件),并创建上传文件的缩略图。
本教程已经假定您具备 .NET Web Forms 和 C# 的基本知识。
顺便说一下,感谢 Konstantin Vasserman 提供的上传代码。 如果您需要将图像上传到数据库,请查看他的 文章。
- 创建一个新的 Web 应用程序项目。
- 打开 Web 表单。
- 从 HTML 选项卡添加一个文件字段到您的表单,并将其转换为服务器控件。 在此示例中,文件字段将命名为 filUpload。
(要将任何 HTML 标签转换为服务器控件,请右键单击它并选择 Run As Server Control(作为服务器控件运行)。)
- 切换到 HTML 视图,并将 form 标签的 enctype 属性添加/更改为 multipart/form-data。
示例:enctype="multipart/form-data"
- 在表单上添加一个 Web Form Button,并将其命名为 btnUpload。
- 在 Web 应用程序中添加一个名为 /images 的文件夹。
- 在表单上添加一个 Web Form Image,并将其命名为 imgPicture。 将宽度调整为 160,高度调整为 120。
- 添加一个 Label,名为 lblOutput。 这将返回任何上传失败的错误信息。
- 在 btnUpload Click 事件中,添加以下代码。
(如果您想详细分析下面的代码,最好将其复制并粘贴到 VS.NET IDE 中,因为有些行很长。)
private void btnUpload_Click(object sender, System.EventArgs e) { // Initialize variables string sSavePath; string sThumbExtension; int intThumbWidth; int intThumbHeight; // Set constant values sSavePath = "images/"; sThumbExtension = "_thumb"; intThumbWidth = 160; intThumbHeight = 120; // If file field isn’t empty if (filUpload.PostedFile != null) { // Check file size (mustn’t be 0) HttpPostedFile myFile = filUpload.PostedFile; int nFileLen = myFile.ContentLength; if (nFileLen == 0) { lblOutput.Text = "No file was uploaded."; return; } // Check file extension (must be JPG) if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg") { lblOutput.Text = "The file must have an extension of JPG"; return; } // Read file into a data stream byte[] myData = new Byte[nFileLen]; myFile.InputStream.Read(myData,0,nFileLen); // Make sure a duplicate file doesn’t exist. If it does, keep on appending an // incremental numeric until it is unique string sFilename = System.IO.Path.GetFileName(myFile.FileName); int file_append = 0; while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename))) { file_append++; sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".jpg"; } // Save the stream to disk System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create); newFile.Write(myData,0, myData.Length); newFile.Close(); // Check whether the file is really a JPEG by opening it System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); Bitmap myBitmap; try { myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename)); // If jpg file is a jpeg, create a thumbnail filename that is unique. file_append = 0; string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + sThumbExtension + ".jpg"; while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile))) { file_append++; sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + sThumbExtension + ".jpg"; } // Save thumbnail and output it onto the webpage System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero); myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); imgPicture.ImageUrl = sSavePath + sThumbFile; // Displaying success information lblOutput.Text = "File uploaded successfully!"; // Destroy objects myThumbnail.Dispose(); myBitmap.Dispose(); } catch (ArgumentException errArgument) { // The file wasn't a valid jpg file lblOutput.Text = "The file wasn't a valid jpg file."; System.IO.File.Delete(Server.MapPath(sSavePath + sFilename)); } } } public bool ThumbnailCallback() { return false; }
- 运行网页,并使用 JPG 文件和其他文件进行测试,以测试错误检查机制。
- 如果您有任何问题/建议,请在下方留言。 :-)