使用相同会话的httpwebrequest上传文件

时间:2014-02-18 13:23:46

标签: vb.net session file-upload awesomium

我受到Awesomium的启发,我试图使用它作为我的客户端应用程序,使用vb.net进行我的Web应用程序。我试图做一个上传器模块,我们的clinets可以将任何文件上传到我们的服务器。我使用HttpWebRequest来上传工作正常的文件。但唯一的问题是当我登录我的web应用程序到httpwebrequest时如何设置由Awesomium创建的会话。或者是否有任何其他方式在awesomium本身上传文件到服务器(即PHP服务器)。

请道歉我的英语不好。

下面是我用于上传的代码

    Dim filepath As String = Path  'Path to file on local machine 

    Dim url As String = "http://xxxxx.com/uploadscanfile.php"

    Dim boundary As String = IO.Path.GetRandomFileName
    ImageRandomName.Add(IO.Path.GetFileName(filepath))

    Dim header As New System.Text.StringBuilder()
    header.AppendLine("--" & boundary)
    header.Append("Content-Disposition: form-data; name=""file"";")
    header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(filepath))
    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(filepath).Length + endboundarybytes.Length

    req.AllowAutoRedirect = True
    req.Timeout = -1
    req.KeepAlive = True
    req.AllowWriteStreamBuffering = False
    req.Method = "POST"
    Dim s As IO.Stream = req.GetRequestStream
    s.Write(headerbytes, 0, headerbytes.Length)
    Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(filepath)
    s.Write(filebytes, 0, filebytes.Length)
    s.Write(endboundarybytes, 0, endboundarybytes.Length)
    s.Close() 

1 个答案:

答案 0 :(得分:0)

通常,会话信息存储在cookie中。因此,您首先需要发送登录数据(并收到回复)。此外,在收到回复时,您需要在CookieContainer属性中设置CookieContainer,稍后您将重复使用它。只有这样,您才能发送表单数据并上传文件,但请确保在上传时将CookieContainer设置为包含Cookie的CookieContainer

在登录时查看进出服务器的所有请求/响应的好方法,我建议您使用Fiddler这是一个非常有用的工具,可以监视您所做的所有请求。请注意标题,发送的数据以及您可能觉得有用的任何其他内容。

更多代码:

以下是使您登录的部分:您发送的帖子字符串需要包含用户名和密码。 (以及可能需要的任何其他信息)。

    Dim CookieJar As New CookieContainer()    'The CookieContainer that will keep all the cookies. 
                                              'DO NOT CLEAR THIS BETWEEN REQUESTS! ONLY CLEAR TO "Log Out".

    Dim req As HttpWebRequest = HttpWebRequest.Create("<login URL goes here>")

    req.Method = "POST"
    req.Accept = "text/html, application/xhtml+xml, */*"   'This may be a bit different in your case. Refer to what Fiddler will say.
    req.CookieContainer = CookieJar
    req.ContentLength = post_str.Length
    req.ContentType = "application/x-www-form-urlencoded"    'Also, any useragent will do.
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
    req.Headers.Add("Accept-Language", "en-US,en;q=0.7,ru;q=0.3")
    req.Headers.Add("Accept-Encoding", "gzip, deflate")
    req.Headers.Add("DNT", "1")       'Make sure to add all headers that you found using Fiddler!
    req.Headers.Add("Pragma", "no-cache")

    Dim RequestWriter As New IO.StreamWriter(req.GetRequestStream())
    RequestWriter.Write(post_str)      'Write the post string that contains the log in, password, etc.
    RequestWriter.Close()
    RequestWriter.Dispose()

    Dim ResponceReader As New IO.StreamReader(req.GetResponse().GetResponseStream())
    Dim ResponceData As String = ResponceReader.ReadToEnd()
    ResponceReader.Close()
    ResponceReader.Dispose()

    req.GetResponse.Close()

    'In the long run, you can check the ResponceData to verify that the log in was successful.

以下是CookieJar用于发送请求的地方:

    post_str = ""   'What needs to be sent goes in this variable.

    req = HttpWebRequest.Create("<page to send request to goes here>")

    req.Method = "POST"
    req.Accept = "text/html, application/xhtml+xml, */*"   'May be different in your case
    req.CookieContainer = CookieJar    'Please note: this HAS to be the same CookieJar as you used to login.
    req.ContentLength = post_str.Length
    req.ContentType = "application/x-www-form-urlencoded"
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
    req.Headers.Add("Accept-Language", "en-US,en;q=0.7,ru;q=0.3")
    req.Headers.Add("Accept-Encoding", "gzip, deflate")
    req.Headers.Add("DNT", "1")     'Add all headers here.
    req.Headers.Add("Pragma", "no-cache")

    RequestWriter = New IO.StreamWriter(req.GetRequestStream())
    RequestWriter.Write(post_str)
    RequestWriter.Close()
    RequestWriter.Dispose()

    ResponceReader = New IO.StreamReader(req.GetResponse().GetResponseStream())
    ResponceData = ResponceReader.ReadToEnd()
    ResponceReader.Close()
    ResponceReader.Dispose()

    req.GetResponse.Close()

    'You may want to read the ResponceData.

希望这有帮助。