c#上传文件并限制上传文件类型
作者:admin 日期:2009-01-07
下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该示例只允许上载扩展名为 .doc 或 .xls 的文件。调用 Path.GetExtension 方法来返回要上载的文件的扩展名。如果文件扩展名为 .doc 或 .xls,则调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadBtn_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
string savePath = @"c:\temp\uploads";
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
// Get the name of the file to upload.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the uploaded file.
string extension = System.IO.Path.GetExtension(fileName);
// Allow only files with .doc or .xls extensions
// to be uploaded.
if ((extension == ".doc") | (extension == ".xls"))
{
// 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 that their file was successfully uploaded.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user why their file was not uploaded.
UploadStatusLabel.Text = "Your file was not uploaded because " +
"it does not have a .doc or .xls extension.";
}
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadBtn"
Text="Upload file"
OnClick="UploadBtn_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
广告位
如果要彻底限制上传的文件类型,还需要用到PostFile对象的ContentType属性。ContentType属性的功能是获取客户端发送的文件的 MIME (注一)内容类型,由于浏览器在向服务器发送请求前,首先会确定发送内容的MIME类型,并将MIME类型作为信息的一部分提交到服务器端,因此,有了MIME类型信息(注二),就可以准确知道上传文件的实际类型了。
If File1.PostedFile.ContentType <> "application/zip" Then
Label2.Text = "本应用程序只允许上传zip格式的文件,请重新选择!"
这时,如果再采用修改后缀名的方法上传文件就会发现再也无法上传了。