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
dataAs
Byte
(),ByVal
fileNameAs
String
, _
ByVal
fileTypeAs
String
)
Dim
extensionAs
String
='.bin'
Dim
sDestFolderAs
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
fsAs
New
FileStream(fileName, FileMode.OpenOrCreate)
Dim
wAs
New
BinaryWriter(fs)
For
iAs
Integer
= 0To
data.Length - 1
w.Write(data(i))
Next
w.Close()
fs.Close()
End
Sub