Just as a web service can download a binary file to a client, a web service can also receive and process files a client program uploads to the service. The FileUpload web service (Listing 11.7), for example, stores the file that it receives from clients within the server’s Upload folder. (You will need to create the folder on your server.) To run the web service, you may need to change file permissions on your server to allow the service to access the Media folder. To create the FileUpload web service, perform these steps:
Within Visual Studio .NET, select the File menu New Project option. Visual Studio .NET will display the New Project dialog box.
Within the New Project dialog box Project Types list, click Visual Basic Projects. Then, within the Templates field, click ASP.NET Web Service. Finally, within the Location field, specify the folder within which you want to store the program and the program name FileUpload. Select OK. Visual Studio .NET will display a page onto which you can drag and drop the service’s components.
Select the View menu Code option. Visual Studio .NET will display the program’s source code. Within the source code add the program statements in Listing 11.7.
Listing 11.7 FileUpload.asmx.vb
Imports System.IO <WebMethod()> Public Function FileUpload(ByVal FileData() As Byte, _ Ä ByVal Name As String) As Integer Dim Status As Integer = 0 Dim OutputFile As FileStream Dim FileLength As Long Try Name = "C:\Upload\" + Name OutputFile = File.Open(Name, FileMode.Create, FileAccess.Write) FileLength = FileData.Length OutputFile.Write(FileData, 0, FileLength) OutputFile.Close() Status = 1 Catch Ex As Exception Throw Ex End Try FileUpload = Status End Function
The web service’s processing is essentially the opposite of the processing done by the other services you have created throughout this chapter. Rather than reading a file’s contents into a byte array that a method then returns to the caller, this service receives the byte array from the caller. Then, the service simply writes the array’s contents to a file within the server’s Upload folder.