Introduction:

This blog is all about how to upload file using WCF Services and use it in any client application.

Uploading a File to the server

For this purpose, I am creating a WCF Service. In the ServiceContract attribue, I am taking a Upload method which accepts the Instance of PictureFile class.

Step 1:

Code:

' NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
<ServiceContract()> _
Public Interface IPictureService

<OperationContract()> _
Function Upload(picture As PictureFile) As
Boolean


' TODO: Add your service operations here


End Interface
<DataContract()> _
Public Class PictureFile

<DataMember()> _
Public Property PictureName() As
String
Get
Return m_PictureName
End
Get
Set(value As String)
m_PictureName = Value
End
Set
End Property
Private m_PictureName As String

<DataMember()> _
Public Property PictureStream() As Byte()
Get
Return m_PictureStream
End
Get
Set(value As Byte())
m_PictureStream = Value
End
Set
End Property
Private m_PictureStream As Byte()

End Class

Step 2: The Service.vb code is:

' NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.

Public Class
PictureService
Implements IPictureService

Public Function Upload(picture As PictureFile) As
Boolean

Dim fileStream As FileStream =
Nothing

Dim writer As BinaryWriter =
Nothing

Dim filePath As
String

Try


filePath = HttpContext.Current.Server.MapPath("C:\MCNSERVER2\UserProfiles\vkumar\Desktop") + ConfigurationManager.AppSettings("") +picture.PictureName

If picture.PictureName <> String.Empty
Then

fileStream = File.Open(filePath, FileMode.Create)

writer = New BinaryWriter(fileStream)
writer.Write(picture.PictureStream)
End
If

Return
True

Catch generatedExceptionName As
Exception


Return
False
Finally


If fileStream IsNot Nothing
Then

fileStream.Close()
End
If

If writer IsNot Nothing
Then

writer.Close()

End
If
End Try

End
Function

End Class