C#.NET文件上传的入门学习(FileUpload控件的入门学习)

     上传文件,如果你没有学习过,可能会觉得很难,但是如果你知道我是怎么实现的话,我想啊,你做梦都会笑,因为那也太简单了。当然拉,我这里完全是入门级的例子。也只限于完全没有思路的同僚来学习的。因为这里没有做任何的限制,就只是简单的上传,更深入的学习当然还是需要大家再去努力学习了。

     我啊,喜欢抛砖引玉,希望以这样的方式跟大家一起学习。如果你也是一样刚入门的话,我想啊,咱们就是知音。我希望大家都能以这样的方式来共享自己的收获,毕竟智慧的碰撞更能产生认知的火花。好拉,进入今天的主题吧。

     我的例子是基于webform的,所以你就需要新建一个网站,当然拉,你还需要在这个工程里面新建一个目录(文件夹)来存放你所需要上传的文件,此处是新建一个UploadedImages文件夹在根目录里。例子将在Default.aspx里实现。

     首先,Default.aspx的代码如下:(其实就是拖一个FileUpload,一个按钮和一个标签)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 无标题页



     最后就是Default.aspx.cs里的代码:

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. String savePath = @"D:/WebSite/FileUpload/UploadedImages/"; // Before attempting to perform operations // on the file, verify that the FileUpload // control contains a file. if (FileUpload1.HasFile) { // Get the name of the file to upload. String fileName = FileUpload1.FileName; // Append the name of the file to upload to the path. savePath += fileName; // Call the SaveAs method to save the // uploaded file to the specified path. // This example does not perform all // the necessary error checking. // If a file with the same name // already exists in the specified path, // the uploaded file overwrites it. FileUpload1.SaveAs(savePath); // Notify the user of the name of the file // was saved under. UploadStatusLabel.Text = "Your file was saved as " + fileName; } else { // Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload."; } } }

其实这个例子是在MSDN里面的例子,我啊,只是为你们把它找出来,让你们更方便的学习。上面的例子应该说最简化了。

按钮事件里的方法主要就是先用if条件来判断FileUpload控件里面有没有文件,即if (FileUpload1.HasFile)其实我认为就是里面有没有内容。当if条件为真时,我们就可以通过FileUpload1.FileName  来获取我们所要保存的文件名,并用下面的FileUpload1.SaveAs(savePath)   上传文件。当然了,这样的实现方法都不妥的,因为很可能由于上传久了之后,文件名字重复会出现覆盖的问题,这里我还没有去实验过,只是一时的想法。

    今天就简单的介绍到这里,(^_^)赶着回家了,写得不好,大家多多包涵。希望能和大家一起共勉!Bye-bye.

你可能感兴趣的:(C#-控件)