Tuesday 5 May 2009

Posting an Image to a Web Page in asp.net

I recently had to write an application that was able to upload images to a website in order to be filed away and used by it's photo gallery pages. All I did to put this in place was make a timer which periodically checked for new images in a local folder. When it finds new images it loops through the files and passes each image to a posting function. After a successful post the image gets archived away by the local application. The website performs it's own local file and database functions to file away the image and the job is done! Let's look at some snippets:

The business end of the windows app....

Dim postURL as string = "http://www.yourwebsite.com/somepage.aspx"

Private Sub uploadImage(ByVal theImage As Image, ByVal filename As String)

theImage = processImage(theImage) 'this is a function I use for some intelligent resizing of the image
Dim tempFileName As String = Path.GetTempFileName
theImage.Save(tempFileName)

Dim myHTTPRequest As New WebClient
Dim myHTTPResponse As Byte() = myHTTPRequest.UploadFile(postURL, "POST", tempFileName)

End Sub


The website code to get the image...

Page.Response.ContentType = "image/jpg"


Dim myimage As Byte() = New Byte(Page.Request.ContentLength - 1) {}
Dim uppedImage As HttpPostedFile = Request.Files.Item(0)
uppedImage.InputStream.Read(myimage, 0, CInt(Request.Files.Item(0).ContentLength))


Dim theImage As Image
theImage = Image.FromStream(uppedImage.InputStream())
theImage.Save("C:\mylocalsite\" & getImageName() & ".jpg") 'getImageName just returns a unique date stamped file name

No comments: