gpt4 book ai didi

vb.net - 上传多个文件 (VB.Net)

转载 作者:行者123 更新时间:2023-12-02 09:01:00 25 4
gpt4 key购买 nike

我尝试使用 VB.Net 代码上传多个文件,但没有成功。当有多个文件时,我最终在网络服务器上只有一个文件(对于多个元素,FileExistsTrue)。如果我在其他某个地方完成循环,则会引发异常。

这是我的代码:

Imports System.Net
Imports System.IO

Sub upload()
Dim filepath As String = IO.Path.Combine(Application.StartupPath, "C:\i.bmp")
Dim filepath2 As String = IO.Path.Combine(Application.StartupPath, "C:\i.txt")
Dim url As String = "http://localhost/SEND/MultUp.php"

Dim Element As Object
Dim sNames(0 To 3) As String 'Array declaration

sNames(0) = filepath2
sNames(1) = ""
sNames(2) = ""
sNames(3) = filepath

Dim boundary As String = IO.Path.GetRandomFileName
Dim header As New System.Text.StringBuilder()

For Each Element In sNames 'Roaming all elements of array
If File.Exists(Element) Then
header.AppendLine("--" & boundary)
header.Append("Content-Disposition: form-data; name=""files[]"";")
header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(Element))
header.AppendLine()
header.AppendLine("Content-Type: application/octet-stream")
header.AppendLine()

Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundary & "--" & vbNewLine)

Dim req As Net.HttpWebRequest = Net.HttpWebRequest.Create(url)
req.ContentType = "multipart/form-data; boundary=" & boundary
req.ContentLength = headerbytes.Length + New IO.FileInfo(Element).Length + endboundarybytes.Length
req.Method = "POST"

Dim s As IO.Stream = req.GetRequestStream
s.Write(headerbytes, 0, headerbytes.Length)
Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(Element)
s.Write(filebytes, 0, filebytes.Length)
s.Write(endboundarybytes, 0, endboundarybytes.Length)
s.Close()

header.clear() 'this was missing in my original source code
End If
Next
End Sub

最佳答案

完全归功于jmcilhinney's comment :

最初发布的代码缺少 header.clear() 调用。因此,当处理多个元素时,header 变量继续追加行。

更好的做法是在 For Each 循环中声明 header StringBuilder 变量。它使得它easier to maintain ,编译器应该以任何一种方式优化它。由于 header 不在循环之外使用,因此应该在最窄的范围内使用它。

关于vb.net - 上传多个文件 (VB.Net),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com