避免覆盖同名文件

我们在上一节设计的文件上传和接收示例中,如果多个用户上传了同名的文件,会出现覆盖的情况。

为避免同名文件被覆盖,我们可以将
HttpRequest事件代码改为:

Select Case e.Path
    Case "upload.htm"
        Dim sb As New StringBuilder
        sb.appendLine("<form enctype='multipart/form-data' action='accept.htm' method='post'
id='form1' name='form1'>")
        sb.appendLine(
"
单文件上传: <input type='file' name='up1' id='up1'><br/><br/>")
        sb.appendLine(
"
多文件上传: <input type='file' name='up2' id='up2' multiple><br/><br/>")
        sb.appendLine(
"<input Type='submit' name='Sumbit' id='Sumbit' value='
确定'>")
        sb.appendLine("</form>")
        e.WriteString(sb.ToString)
    Case "accept.htm"
        Dim sb As New StringBuilder
        For Each key As String In e.Files.Keys
            sb.AppendLine(key &
"
上传" & e.Files(key).Count & "个文件,分别是:</br>")
            For Each fl As String In e.Files(key)
                Dim NewName As String = fl
                Dim idx As Integer = fl.LastIndexOf(".")
                Dim cnt As Integer = 1
                Do While FileSys.FileExists("d:\web\uploadfiles\" & NewName)
'
判断文件夹是否存在同名文件
                    NewName = fl.Insert(idx,"(" & cnt & ")")
'
如果存在同名文件,在原文件名加上序号
                    cnt = cnt + 1
'
递增序号
                Loop
                sb.AppendLine(fl &
"
" & NewName & "<br>") '
                e.SaveFile(key,fl,"d:\web\uploadfiles\" & NewName)
'
保存接收到的文件
           
Next
            sb.AppendLine("</br>")
        Next
        sb.AppendLine("以上文件服务器已正确接收并保存!")
        e.WriteString(sb.ToString)

End
Select

这样HttpServer接收到同名文件后,会自动给同名文件加上编号,而不是直接覆盖:


本页地址:http://www.foxtable.com/mobilehelp/topics/0033.htm