Upload file contents to webserver using Post

Good afternoon,
Ive been trying to look around the internet for a solution to this problem, and hanvt really found any solutions.

Im trying to open a file, and then post the contents of the file via HTTP using post, it is part of a larger project, and I need to be able to post the data via HTTP using post or get (pref Post), only issue is, I have no idea how to post data as part of a http request.

I have attached the code I have so far working, and the line with "Dim d As Byte() = System.Text.Encoding.ASCII.GetBytes("fileID=47569")" I belive should be something like "Dim d As Byte() = System.Text.Encoding.ASCII.GetBytes("fileID=47569&fileContents=8Fd56fb2312")", where  8Fd56fb2312 is the hex of the files contents.

The file contents I can see in what I belive is Hex using a watch in the variable rawData, and this is what I need to convert into some type of string to upload, but not got a clue how!!!

It doesnt need to he hex, as once its on the web server, I want PHP to actually read it and write it to a file.

Any help would be appriciated on this one.

Thank you

Imports System.Net
Module Module1
    Sub Main()
        Dim rawData() As Byte
        Dim fs As FileStream
        Dim FileSize As Long

        fs = New FileStream("c:\myFile.jpg", FileMode.Open, FileAccess.Read)
        FileSize = fs.Length
        rawData = New Byte(FileSize) {}
        fs.Read(rawData, 0, FileSize)
        fs.Close()


        Dim wc As New System.Net.WebClient()
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
        Dim d As Byte() = System.Text.Encoding.ASCII.GetBytes("fileID=47569") 
        Dim res As Byte() = wc.UploadData("http://localhost/PostTest.php", "POST", d)
        Dim myResponse As String = System.Text.Encoding.ASCII.GetString(res)
        MsgBox(myResponse)
    End Sub
End Module

Open in new window

tonelm54Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tonelm54Author Commented:
The example-code.com uses a purchasable component called Chilkat which I dont want to do :-(

The aspheute tells me how to read the file and convert it to ascii, but how can I add it as a parameter as the contents of the file contains = and & which are reserved for parameters as far as Im aware, and cannot be used?

Any ideas?
0
David L. HansenCEOCommented:
Ok,

I know I'm just giving you a bunch of urls instead of posting some nice clean code for you...sorry.  Give these two more urls a try and if you don't discover exactly what you need in them, then I'll comb through the code with you and find just what you are looking for.

So here they are:
http://www.4guysfromrolla.com/webtech/012401-1.shtml
and
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8519&lngWId=4
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

tonelm54Author Commented:
Sorry,
Call me dumb, but again they dont seem to be what Im looking for.

The actuall idea is to open a file, split it into chunks and upload each chuck via HTTP and have a php file re-assembly the file on the server.

Currently the idea is to take a small file and figure out how to do the entire file, then I can work on seperating the file into chunks and upload each chunk.

The code I have at the moment seems to work, in the fact it sends data to the php script and it writes the file, however the resulting file doesnt open.

When I open the resulting file up, its just numbers, so obviously wont open.

The php code seems to be working, as its writing what is posted in the varible 'strContents' in the VB code, however the 'strContents' doesnt seem to hold the file contents correctly, and me being dumb cant seem to figure out how to convert the bits into a string correctly, and then pass that accross into a HTTP header :-S

For example, the file I open the first but is:-
          ÿØÿá&[Exif  II*        ’   
However the end file is:-
          2552162552253891691201051020073734208000

The PHP code I have is quite simple to test the it:-
          <?php
                    $myFile = "testFile.jpg";
                    $fh = fopen($myFile, 'w');
                    fwrite($fh, $_POST['fileContent']);
                    fclose($fh);
          ?>

The VB.net code is attached

I hope this makes sence :-S

Thank you
Imports System.Net
Imports System.IO

Module Module1
    Sub Main()
        Dim rawData() As Byte
        Dim fs As FileStream
        Dim FileSize As Long

        fs = New FileStream("c:\myFile.jpg", FileMode.Open, FileAccess.Read)
        FileSize = fs.Length
        rawData = New Byte(FileSize) {}
        fs.Read(rawData, 0, FileSize)
        fs.Close()

        Dim strContents As String = ""

        For Each tmpBit In rawData
            strContents = strContents & tmpBit
        Next

        Dim wc As New System.Net.WebClient()
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
        Dim d As Byte() = System.Text.Encoding.ASCII.GetBytes("fileID=47569&fileContent=" & strContents)
        Dim res As Byte() = wc.UploadData("http://localhost/PostTest.php", "POST", d)
        Dim myResponse As String = System.Text.Encoding.ASCII.GetString(res)
        MsgBox(myResponse)
    End Sub
End Module

Open in new window

0
David L. HansenCEOCommented:
What is tmpBit?  Also, it appears that you are working with a jpg image; I thought you wanted to upload a text file.  Am I missing something?
0
tonelm54Author Commented:
tmpBit is a byte, which I thought I could then put the bytes data into a string, and then put that string into the header data as a post for the http request.

The jpg is just a file for testing, I would like it to work with pdfs xls tiffs etc, in other words any type of file.

So the idea is to load the file (well a chunk of it in the end) and convert it into a string or similar and upload it as a http request.

Sorry, its probably me not explaining things :-(

Thank you

Does that make sence
0
B_DorseyCommented:
I jsut finished one with a progress bar, maybe it will help

http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_25727189.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David L. HansenCEOCommented:
B Dorsey seems to be on the right track.  I was hoping to help but....
0
tonelm54Author Commented:
Ive looked at the code from 'B Dorsey' and adapted as attached, but Im getting the same error as 'B Dorsey' on the line s.Close():-
          The request was aborted: The request was canceled.

Not sure if Im going the right way, as cant see how I can pull the data back in PHP using $_POST.

If I can get this working, hopefully I can then examine the headers and figure out whats going on.
Imports System.Net
Imports System.IO
Imports System
Imports System.Security.Permissions
Imports System.Threading




Module Module1
    Sub Main()
        Dim filepath As String = "c:\myFile.jpg"
        Dim url As String = "http://localhost/PostTest.php"

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

        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.Method = "POST"

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

        Dim pbSpeed = 1000
        Dim intChunk = filebytes.Length / pbSpeed

        Dim intOffSet = 0
        For I As Integer = 1 To pbSpeed
            If intOffSet + intChunk > filebytes.Length Then intChunk = filebytes.Length - intOffSet
            s.Write(filebytes, intOffSet, intChunk)
            intOffSet += intChunk
        Next
        s.Write(endboundarybytes, 0, endboundarybytes.Length)

        req.Timeout = Timeout.Infinite

        s.Flush()
        s.Close()

        Dim response As WebResponse = req.GetResponse()
        Dim ss As Stream = response.GetResponseStream
        Dim sr As StreamReader = New StreamReader(ss)
        MsgBox(sr.ReadToEnd.ToString)
    End Sub
End Module

Open in new window

0
tonelm54Author Commented:
sl8rz-> Just having another brain working on the problem helps, belive me :-)

Thank you for your help up till now!!
0
B_DorseyCommented:
go back to my question, I found the answer... I will repost mine working shortly... i got rid of the error...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.