这与我的previous question有关。 Wizard控件出现了一个无法预料的问题。向导控件中的文件上传,在末尾处理
我现在知道如何上传到FTP,然而使用时FileUpload控件向导控制,里面,当你移动到下一个步骤,该文件您选择得到,因为回传的清除。我需要能够在上传之前根据向导的结果重命名文件。所以......
- 我完成我的向导
- 它上传一些东西到数据库
- 根据这些结果重命名文件
- 上传重命名的文件到FTP服务器
我怀疑我需要按照这样的程序,在FileUpload旁边有一个上传按钮
- 在“上传”按钮上单击将文件流式传输到Web服务器。
- 完成向导。
- 如果向导成功完成,请将文件和流重命名为FTP服务器。
- 如果向导失败了,什么?从网络服务器上删除文件?怎么样?
我想我了解的过程,所以我想就如何我的FTP上传功能分为两个部分用正确的错误处理时,向导未能帮助。
如果您使用下面的代码作为基础,这将是一个很大的帮助。感谢一如既往:)
Protected Sub UploadFile(ByVal NewFilename As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Function one? - Problem, "NewFilename" depends on the output of the Wizard,
' but obviously it has not been called yet.
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + NewFilename), FtpWebRequest)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
Dim myFileStream As Stream = FileUpload1.FileContent
myFtpWebRequest.ContentLength = myFileStream.Length
'Function two?
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
- 答案---
这是我基于输入来自伊卡洛斯最终实现:)
为了简便起见我已经排除了错误捕获。该文件被上传到网络服务器
'This function is what kicks things off...
Protected Sub UploadFileToWebServer() Handles btnUploadFile.Click
Dim TempDir As String = "C:\TEMP", FileName As String = "uploadedfile.tmp", FilePath As String
If Not Directory.Exists(TempDir) Then
Directory.CreateDirectory(TempDir).Attributes = FileAttributes.Directory
End If
FilePath = TempDir + "\" + FileName
Session.Add("FileName", File1.FileName) 'Keep track of uploaded file name
File1.SaveAs(FilePath)
Session.Add("File", FilePath)
End Sub
后,我们就可以继续通过该向导,点击“完成”按钮时,向导数据被提交到数据库。文件名基于插入的记录ID。插入记录后,通过点击“最终”按钮,下列函数被调用,并且该文件最终被上传到FTP服务器,文件名相应地发生了变化。
Protected Sub UploadFileToFtpServer(ByVal FileLinkStr As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Defines the filename, path, and upload method, and connection credentials
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + FileLinkStr), FtpWebRequest)
'Be sure to authenticate prior to uploading or nothing will upload and no error
myFtpWebRequest.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
'Streams the file to the FTP server
'Retrieves File temporarily uploaded to the Web Server during Wizard Processing
Dim iStream As New FileInfo(Session.Item("File"))
Dim myFileStream As Stream = iStream.OpenRead
myFtpWebRequest.ContentLength = myFileStream.Length
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
好,我很高兴它的作品! – Icarus