[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Upload file contents to webserver using Post

Posted on 2010-04-06
11
Medium Priority
?
498 Views
Last Modified: 2012-06-27
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

0
Comment
Question by:tonelm54
  • 5
  • 4
  • 2
11 Comments
 
LVL 15

Expert Comment

by:David L. Hansen
ID: 29911788
0
 

Author Comment

by:tonelm54
ID: 29920296
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
 
LVL 15

Expert Comment

by:David L. Hansen
ID: 29922735
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
Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

 

Author Comment

by:tonelm54
ID: 29925460
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
 
LVL 15

Expert Comment

by:David L. Hansen
ID: 29927127
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
 

Author Comment

by:tonelm54
ID: 29935513
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
 
LVL 14

Accepted Solution

by:
B_Dorsey earned 2000 total points
ID: 29937609
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
 
LVL 15

Expert Comment

by:David L. Hansen
ID: 29938601
B Dorsey seems to be on the right track.  I was hoping to help but....
0
 

Author Comment

by:tonelm54
ID: 29949368
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
 

Author Comment

by:tonelm54
ID: 29949483
sl8rz-> Just having another brain working on the problem helps, belive me :-)

Thank you for your help up till now!!
0
 
LVL 14

Expert Comment

by:B_Dorsey
ID: 29966675
go back to my question, I found the answer... I will repost mine working shortly... i got rid of the error...
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The video will let you know the exact process to import OST/PST files to the cloud based Office 365 mailboxes. Using Kernel Import PST to Office 365 tool, one can quickly import numerous OST/PST files to Office 365. Besides this, the tool also comes…
Free Data Recovery software is an advanced solution from Kernel Tools to recover data and files such as documents, emails, database, media and pictures, etc. It supports recovery from physical & logical drive after a hard disk crash, accidental/inte…
Suggested Courses

612 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question