Upload several files just by a click
Nowadays, Internet becomes more and more important to people around the world. People are enjoying the fun of sharing resources in every aspect, such as music, movies, news, codes and even their secrets. We can easily think of youtube, tudou, namipan…but how to upload the resources may be a problem to you.
In fact, it’s very easy to upload single file once, just with a “FileUpload” and a “button” controller. There’s only one line of key code:
FileUpload1.SaveAs(Server.MapPath("")+"//" + FileUpload1.FileName); //save it where you want
How about uploading several files at the same time? If you take it for granted and say, just rewrite the sentence several times is OK, you must get into trouble, because it is unfeasible when the number of the files is big. This time we should change our minds to another way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
string filepath = Server.MapPath("") + "//";
HttpFileCollection uploadFiles = Request.Files; //create an objection to the upload files.
for (int i = 0; i < uploadFiles.Count; i++)
{
HttpPostedFile postedFile = uploadFiles[i];
try
{
if (postedFile.ContentLength > 0)
{
Label1.Text += "文件" + (i + 1) + ":" + System.IO.Path.GetFileName(postedFile.FileName) + "<br/>";//print file //information
postedFile.SaveAs(filepath + System.IO.Path.GetFileName(postedFile.FileName));//save them where you want
}
}
catch (Exception Ex) //exception procession
{
Label1.Text += "发生错误: " + Ex.Message;
}
}
}
}
图1
图2
Firstly, create an objection to the uploadfile collection. Secondly, create a instance to the uploadfile. Finally, post the files with a method of SaveAs().