Uploading a File Through a Web Service

This topic intimidated me when it first presented itself to me, because let's face it a Web Service really looks like it just processes XML and objects serialized essentially into a text format. Once I did a little investigating I found that it really is not that hard and can be used for a good thing, including cross platform interactions.

The big secret is passing an array of bytes as a parameter and then using the BinaryWriter to store the bits to a file. The following example shows how to pass the byte array, a file name and a file MIME type to store the file locally. Of course the web server has to have write permissions on the destination folder.

    <WebMethod()> _
    

Public

Sub

UploadBinaryFile(

ByVal

data

As

Byte

(),

ByVal

fileName

As

String

, _

ByVal

fileType

As

String

)
 
        

Dim

extension

As

String

=

'.bin'

Dim

sDestFolder

As

String

=

String

.Empty
 
        

If

fileType.Equals(

'application/pdf'

)

Then

            extension = 

'.pdf'

        

ElseIf

fileType.Equals(

'image/tiff'

)

Then

            extension = 

'.tiff'

        

ElseIf

fileType.Equals(

'image/jpeg'

)

Then

            extension = 

'.jpg'

        

ElseIf

fileType.Equals(

'image/gif'

)

Then

            extension = 

'.gif'

        

ElseIf

fileType.Equals(

'image/png'

)

Then

            extension = 

'.png'

        

ElseIf

fileType.Equals(

'image/zip'

)

Then

            extension = 

'.zip'

        

Else

            extension = 

'.bin'

        

End

If

 
        

' This is not a complete routine, but enough to suffice for this demo.

        

If

fileName.EndsWith(extension) =

False

Then

            fileName = fileName & extension
        

End

If

 
        fileName = sDestFolder & fileName
 
        

Dim

fs

As

New

FileStream(fileName, FileMode.OpenOrCreate)
        

Dim

w

As

New

BinaryWriter(fs)
        

For

i

As

Integer

= 0

To

data.Length - 1
            w.Write(data(i))
        

Next

 
        w.Close()
        fs.Close()
    

End

Sub

Share This Article With Your Friends!

We use cookies to give you the best experience possible. By continuing, we'll assume you're cool with our cookie policy.

Install Love2Dev for quick, easy access from your homescreen or start menu.

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel