Using HttpWebRequest to upload file to PHP url

seinkraft

Member
Joined
Sep 28, 2008
Messages
19
Programming Experience
5-10
Hi everyone, i'm really new with HttpWebRequest and i don't understand it as well but i need it to use an api from my web to post images.

I've this at the moment.
VB.NET:
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader
        Dim address As Uri
        Dim data As StringBuilder
        Dim byteData() As Byte
        Dim postStream As Stream = Nothing

        Dim username As String
        Dim password As String
        Dim file_location As String
        Dim tags As String
        Dim source As String
        Dim md5 As String

        address = New Uri("http://localhost/api/add_image")

        ' Create the web request  
        request = DirectCast(WebRequest.Create(address), HttpWebRequest)

        ' Set type to POST  
        request.Method = "POST"
        request.ContentType = "multipart/form-data"

        ' Create the data we want to send
        username = "sein"
        password = "1234"
        file_location = txtFile.Text
        tags = "coco nu_se"
        source = "http://www.seinkraft.info"
        md5 = "2ef87d61eb6c5d318760db51828d8d00"

        data = New StringBuilder()
        data.Append("login=" + username)
        data.Append("&password=" + password)
        data.Append("&file=" + file_location)
        data.Append("&md5=" + md5)
        data.Append("&tags=" + tags)
        data.Append("&source=" + source)

        TextBox1.Text = data.ToString

        ' Create a byte array of the data we want to send  
        byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())

        ' Set the content length in the request headers  
        request.ContentLength = byteData.Length

        ' Write data  
        Try
            postStream = request.GetRequestStream()
            postStream.Write(byteData, 0, byteData.Length)
        Finally
            If Not postStream Is Nothing Then postStream.Close()
        End Try

        Try
            ' Get response  
            response = DirectCast(request.GetResponse(), HttpWebResponse)

            ' Get the response stream into a reader  
            reader = New StreamReader(response.GetResponseStream())

            ' Console application output  
            TextBox2.Text = reader.ReadToEnd()
        Finally
            If Not response Is Nothing Then response.Close()
        End Try
    End Sub

And the api parameters are:
Parameters
* login: username
* password: password
* file: file as a multipart form
* source: source url
* tags: list of tags as a string, delimited by whitespace
* md5: MD5 hash of upload in hexadecimal format

but i don't know how send the file as multipart.

Anyone can help me?

(sorry about my poor english)
 
Yeah but my api is written in php, and i need to upload a file relize posting to it.

Its the same as a form but instead use $_POST uses $_GET to catch the information.
 
Actually i also have tried that without luck :/

This my POST for the real form. Ive cutted the image stream
VB.NET:
Content-Type: multipart/form-data; boundary=---------------------------236502814911192
Content-Length: 360083

-----------------------------236502814911192
Content-Disposition: form-data; name="data0"; filename="2ef87d61eb6c5d318760db51828d8d00.png"
Content-Type: image/png

‰PNG


IHDR  è     q$Q    IDATxœì½i“%Ç•¦wÎq÷Xî~s«Ê¬¬U 	‚$¸¢¹4§§»§Õ=²6“>Èô—ZÿA-ýÍ}ifL2õ´uS=›$¸
(0ñ°Ê…ög‚¶6ÞÀÞæ*oJš’ `ësŒ1DÈLÖ€1d¬E/ã©Yi3ù§OÒ¢	‡³™>xÌÛc»³E›ÏdÕ¨*×A!'"	Çgq¶ Uª*™ŒÍhPÌŽŸU~£ÓκžPÐ"y •”¯F+²¬x©[àåë%BGàì__AûÛ
ý2eI}H1áÍ«™2}ÿbk»>£ƒb    IEND®B`‚
-----------------------------236502814911192
Content-Disposition: form-data; name="url0"


-----------------------------236502814911192
Content-Disposition: form-data; name="tags"


-----------------------------236502814911192
Content-Disposition: form-data; name="source"


-----------------------------236502814911192--
 
Last edited:
That is exactly the kind of output my code sample will produce, only that code has only one part (the file part). Study the code some more and your sample message, try to identify the structure of the message and how it related to the code. All you have to do is compose all parts and post the message. The order of the parts should not matter, so you should be able to just add these text lines to the existing 'header' StringBuilder.

Consider this Sample File Upload Form for example, instead of the original code that only had a file part I would simply use these lines to post a file with an additional 'note' part:
VB.NET:
Dim header As New System.Text.StringBuilder()
header.AppendLine("--" & boundary)
header.AppendLine("Content-Disposition: form-data; name=""note"";")
header.AppendLine()
header.AppendLine("some note")
header.AppendLine("--" & boundary)
header.Append("Content-Disposition: form-data; name=""upfile"";")
header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(filepath))
header.AppendLine()
header.AppendLine("Content-Type: application/octet-stream")
header.AppendLine()
 
Thank you so much for the example. I've finished that part and is working but now i cant read the response wich should be the id of the uplodaded file.

I'm using the next code with your example:

VB.NET:
Dim webResponse As HttpWebResponse = Nothing
Dim stReader As StreamReader = Nothing

Try
     webResponse = req.GetResponse()
     stReader = New StreamReader(webResponse.GetResponseStream())

    TextBox2.Text = stReader.ReadToEnd()
Finally
    If Not webResponse Is Nothing Then webResponse.Close()
End Try
 
I see no problem with that response reading code, I used basically the same code with the "Sample File Upload Form" and got the expected response text. Do you get any particular StatusCode from the response? Have you looked at the text output (without the file bytes) of your request data to verify that your multipart message composition meets the requirements?
 
well this a part of the php file who send the response:

PHP:
// If it went ok, grab the id for the newly uploaded image and pass it in the header
$newimg = Image::by_hash($hash);
$newid = make_link("post/view/" . $newimg->id);
// Did we POST or GET this call?
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	header("X-Danbooru-Location: $newid");
}
else
{
header("Location: $newid");
}

(this send if the image already exists and the link to the image)
PHP:
if(!is_null($existing)) {
	header("HTTP/1.0 409 Conflict");
	header("X-Danbooru-Errors: duplicate");
	$existinglink = make_link("post/view/" . $existing->id);
	header("X-Danbooru-Location: $existinglink");
}

But i cant read the response and if is readed it only read "409 Conflict" and crashes the app.
 
Back
Top