用FileStream上传文件转换成二进制
用FileStream上传图片转换成二进制,在本地用行,传到服务器上去出现如下错误
未能找到路径“C:/Documents and Settings/xxxxxxx.doc”的一部分。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.IO.DirectoryNotFoundException: 未能找到路径“C:/Documents and Settings/ xxxxxxx.doc”的一部分。
Debug,本地上传没有任何问题。
分析:根据提示“找不到本地路径…”,不是权限的问题。
查阅相关资料,得到出错的结论如下:
1. 程序运行在服务器端,上传文件来自于客户端。
2. FileStream 只支持本地数据流上传,所有会造成本地上传没有问题,上传到服务器时报错。
3. Stream允许远程数据流上传,本地到服务器,本地到本地都没有问题。
修改:将FileStream改成Stream
将代码:
' Dim fs As New FileStream(xHIF.PostedFile.FileName, FileMode.Open, FileAccess.Read)
' Dim br As New BinaryReader(fs)
修改为:
Dim fs As Stream = xHIF.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CInt(fs.Length))
br.Close()
fs.Close()
完整上传文件代码片断
Protected Sub Button_File_Save_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button_Plans_Save.Click
Dim baseLocation = "D:/CAR_Files/"
Try
Dim status = ""
Dim istg_plan_id As String
istg_plan_id = GetPlansID()
If (ListBox_Files.Items.Count = 0) And (filesUploaded = 0) Then
Me.Label_File_Status.Text = "Error - a file name must be specified."
Return
Else
If Me.CreateCar3DPlans(istg_plan_id) = True Then
For Each xHIF As System.Web.UI.HtmlControls.HtmlInputFile In hif
Dim fn As String = System.IO.Path.GetFileName(xHIF.PostedFile.FileName)
Dim l_fn As String
xHIF.PostedFile.SaveAs(baseLocation & fn)
filesUploaded = filesUploaded + 1
status = status & fn & "<br>"
l_fn = baseLocation & fn
' Dim fs As New FileStream(xHIF.PostedFile.FileName, FileMode.Open, FileAccess.Read)
' Dim br As New BinaryReader(fs)
Dim fs As Stream = xHIF.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CInt(fs.Length))
br.Close()
fs.Close()
Dim lf_desc As String
Dim lf_type As String
Dim lf_size As String
lf_desc = System.IO.Path.GetExtension(xHIF.PostedFile.FileName)
lf_type = xHIF.PostedFile.ContentType.ToString
lf_size = xHIF.PostedFile.ContentLength.ToString
CreateCar3DPlansFile(istg_plan_id, fn, lf_desc, lf_type, lf_size, bytes, l_fn)
Response.Write(fn)
Next
End If
If filesUploaded = hif.Count Then
Me.Label_File_Status.Text = "These " & filesUploaded.ToString & " file(s) were uploaded:<br>" + status
End If
hif.Clear()
ListBox_Files.Items.Clear()
End If
GetCar3DPlans()
Catch ex As Exception
Response.Write(ex.ToString)
Me.Label_File_Status.Text = "Error saving file " & baseLocation & "<br>" & Err.ToString()
End Try
End Sub