上传在Web开发中,是非常普遍的一项任务,以前用ASP的时候,一直用稻农的无组件上传工具,觉得很好用,现在学Asp.net了,却发现没有类似原来稻农的无组件上传程序,因此花了点时间,将稻农的无组件上传程序用vb.net改写了一下,可以编译成DLL,在C#或者Vb.net等任意asp.net支持的语言中使用,在共享出来,希望能为大家节约点时间,也欢迎提出意见和建议,让他更完善。
Option Explicit On
Option Strict On
Imports System.IO
Imports System.Data
Imports System.Web.UI.HtmlControls.HtmlInputControl
Public Class UploadFile
'---------------------------------------------------
'欢迎转载,但请保留以下声名
'说明:文件上传类
'创建时间:2004-11-18
'作者:刀尖客 QQ:51978456
--------------------------------------------------------
Private LocOrgFileName As String '原始文件名
Private LocNewFileName As String '新文件名
Private LocUploadDir As String = "" '保存目录 注意:要完整路径
Private LocAllowOverWrite As Boolean = False '如果保存文件已经存在,是否覆盖
Private LocAllowExtFile As String = "doc,jpg,gif,zip" '许可格式
Private LocAllowMaxSize As Integer = 3 * 1024 * 1024 '许可大小
Public ErrMsg As String '返回的错误提示
Public ReadOnly Property OrgFileName() As String
Get
Return LocOrgFileName
End Get
End Property
Public Property NewFileName() As String
Get
Return LocNewFileName
End Get
Set(ByVal strValue As String)
LocNewFileName = strValue
End Set
End Property
Public Property UploadDir() As String
Get
Return LocUploadDir
End Get
Set(ByVal strValue As String)
LocUploadDir = strValue
End Set
End Property
Public Property AllowOverWrite() As Boolean
Get
Return LocAllowOverWrite
End Get
Set(ByVal blnValue As Boolean)
LocAllowOverWrite = blnValue
End Set
End Property
Public Property AllowMaxSize() As Integer
Get
Return LocAllowMaxSize
End Get
Set(ByVal intValue As Integer)
LocAllowMaxSize = intValue
End Set
End Property
Public Property AllowExtFile() As String
Get
Return LocAllowExtFile
End Get
Set(ByVal strValue As String)
LocAllowExtFile = strValue
End Set
End Property
'---------------------------------------------
'功能说明:上传文件到服务器
'参数:file 要上传的文件域 IsRandom 是否采用随机数文件名,如果为Flase,则采用文件原来的名称
'---------------------------------------------
Public Function Upload(ByRef file As System.Web.UI.HtmlControls.HtmlInputFile, Optional ByVal IsRandom As Boolean = True) As Boolean
Dim objFile As file
Dim oldFileName As String
Dim strNewFileName As String
Dim strExtName As String
If file.PostedFile.ContentLength = 0 Then
ErrMsg = "没有上传文件"
Return False
End If
oldFileName = file.PostedFile.FileName
strExtName = GetExtName(oldFileName)
If IsRandom = True Then
LocNewFileName = GetRandomFileName(oldFileName, strExtName)
strNewFileName = LocNewFileName
Else
LocNewFileName = oldFileName
strNewFileName = LocNewFileName
End If
If LocUploadDir <> "" Then
If Directory.Exists(LocUploadDir) = False Then
ErrMsg = "上传目录" & LocUploadDir & "不存在"
Else
If objFile.Exists(strNewFileName) And LocAllowOverWrite = False Then
ErrMsg = "对不起,服务器上此文件已经存在!"
Return False
Else
If InStr(LocAllowExtFile, strExtName) <> 0 Then
&n