FileUpLoad控件的使用
方法一:
protected void btnAdd_Click(object sender, EventArgs e)
{
String root = System.Configuration.ConfigurationManager.AppSettings["upload"];
bool fileOK = false;
String save_path = root;
String time = DateTime.Now.ToString("yyyyMMddhhmmss");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
if (this.FileUpload1.HasFile)
{
save_path += time + FileUpload1.FileName;
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowExtenstion ={ ".gif", ".png", ".bmp", ".jpg", ".jpeg", ".doc", ".txt", ".xls", ".ppt", ".rar", ".zip", ".mdb",".pdf" };
for (int i = 0; i < allowExtenstion.Length; i++)
{
if (fileExtension == allowExtenstion[i])
{
fileOK = true;
}
}
if (fileOK)
{
try
{
FileUpload1.SaveAs(save_path );
Response.Write("<Script language='javascript'>alert('上传成功!!!');</Script>");
}
catch (Exception ex)
{
Response.Write("<Script language='javascript'>alert('上传失败'" + ex.Message + ");</Script>");
}
}
}
else
{
Response.Write("<Script language='javascript'>alert('不支持的文件,请压成rar文件后再上传!');</Script>");
}
}
方法二:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="fileupload.aspx.cs" Inherits="fileupload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
</head>
<body>
</body>
</html>
到了最重要的后台代码显示了,看懂按钮中的事件代码:
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 fileupload : System.Web.UI.Page
{
}
这样就完成了上传图片的操作了,上传视频也可以,但考虑到视频文件大小问题,根据经验大于5M就不是很好了,这时候需要修改Web.config配置文件了,最好还要加一个进度条,让用户清楚上传的进度...[显示进度的知识点我会尽快整理好的].
方法三:
string name = this.FileUpload1.FileName;
string size = FileUpload1.PostedFile.ContentLength.ToString();
string type = FileUpload1.PostedFile.ContentType;
string type2 = name.Substring(name.LastIndexOf(".") + 1);
string ipath = Server.MapPath("upimg") + "\\" + name;
string fpath = Server.MapPath("upfile") + "\\" + name;
string wpath = "upimg\\" + name;
if (type2 == "jpg" || type2 == "gif" || type2 == "bmp" || type2 == "png")
{
FileUpload1.SaveAs(ipath);
Image1.ImageUrl = wpath;
Label1.Text = "Your load file is " + name + "<br>size is:" + size + "byte<br>file style is:" + type + "<br>ext name is :" + type2 + "<br>fac path is :" + ipath + "<br> vir path is:" + wpath;
}
else
{
Image1.Visible = false;
FileUpload1.SaveAs(fpath);
Label1.Text = "Your load file is " + name + "<br>size is:" + size + "byte<br>file style is:" + type + "<br>ext name is :" + type2 + "<br>fac path is :" + ipath + "<br> vir path is:" + wpath;
}