2014-02-27 4 views
3

VB.Net 코드로 여러 파일을 업로드하려고하는데 성공하지 못했습니다. 하나 이상의 파일 (FileExists은 복수 요소의 경우 True)이있을 때 웹 서버에서 단 하나의 파일로 끝납니다. 다른 곳에서 루프를 끝내면 예외가 발생합니다.여러 파일 업로드 (VB.Net)

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 
+6

내가 볼 수있는 한 StringBuilder를 비우지 않으므로 문제가 될 수 있습니다. – jmcilhinney

+0

좋은 제안 @jmcilhinney! 추가 => header.Clear() before => End If 이제 제대로 작동합니다. 고맙습니다. 서버 측에 –

+0

이 있으면 여러 개의 Form1.Requests를 통과하도록 루프를 설정 했습니까? –

답변

0

전체 신용 jmcilhinney's comment에 :

원래 코드가 누락 된 게시 된 header.clear() 전화

이 내 코드입니다. 따라서 여러 요소가 처리 될 때 header 변수가 계속해서 줄을 추가합니다.

더 좋은 방법은 StringBuilder 변수를 For Each 루프 내에 선언하는 것입니다. 그것은 그것을 easier to maintain으로 만들고, 컴파일러는 그것을 어느쪽으로 나 최적화해야합니다. header은 루프 외부에서 사용되지 않으므로 가장 좁은 범위에서 사용해야합니다.