|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article shall describe an approach that may be used to upload any sort of a file through a Web service from a Windows Forms application. The approach demonstrated does not rely on the ASP.NET file uploader control and allows the developer the opportunity to upload files programmatically and without user intervention. Such an approach may be useful for doing something like processing out the contents of a local message queue when Internet service is available (if the user base were mobile and had only intermittent connectivity). The article also addresses the use of a file size check as a precursor to allowing a file to upload through the service.
Figure 1: Test Application Shown Uploading a File.
Figure 2: Mixed bag of different file types in transient storage folder.
Getting StartedThe solution contains two projects; one is a ASP.NET Web Service project (Uploader) and the other is a WinForms test application (TestUploader) used to demonstrate uploading files through the Web method provided in the Web service project. The Web service project contains only a single Web service (
Figure 3: Solution Explorer with both Projects Visible.
Code: Uploader Web Service ProjectThe Uploader Web service project is an ASP.NET Web service project containing a single Web service called, The code for this Web service begins with the following: Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.IO
''' <summary>
''' This Web method will provide a Web method to load any
''' file onto the server; the UploadFile Web method
''' will accept the report and store it in the local file system.
''' </summary>
''' <remarks></remarks>
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class FileUploader
Inherits System.Web.Services.WebService
The class starts out with the default imports; I added The remainder of the code supplied in this class is used to define the Web method used to upload the file; the code is annotated. The essential process is that, files converted to byte arrays are passed along with the full name of the file (not the path) including the extension as arguments to the The Web method is set up to return a string; if all goes well, the string returned will read <WebMethod()> _
Public Function UploadFile(ByVal f As Byte(), ByVal fileName As String) As String
' the byte array argument contains the content of the file
' the string argument contains the name and extension of the
' file passed in through the byte array
Try
' instance a memory stream and pass the byte array
' to its constructor
Dim ms As New MemoryStream(f)
' instance a filestream pointing to the
' storage folder, use the original file name
' to name the resulting file
Dim fs As New FileStream(System.Web.Hosting.HostingEnvironment.
MapPath("~/TransientStorage/") & fileName, FileMode.Create)
ms.WriteTo(fs)
' clean up
ms.Close()
fs.Close()
fs.Dispose()
' return OK if we made it to here
Return "OK"
Catch ex As Exception
Return ex.Message.ToString()
End Try
End Function
Code: Test Uploader Win Forms ApplicationThe test application contains a single Windows The code for this class begins with the following: Imports System.IO
Public Class Form1
Aside from the default imports, I have added only The next bit of code in the class is a private method used to prepare the file for submittal to the Web service and to actually make that submittal. The code below is annotated to describe the activity but the essential parts of the operation are to check the file size to see if the Web service will accept the file (by default, the Web server will accept uploads smaller than 4 MB in size, the web.config file must be updated in order to support larger uploads), and to convert the file to a byte array. When everything is ready, the byte array and the name of the file including the extension is passed to an instance of the Web Service Web method. Note that, when setting up the demo, you will have to remove and add the Web reference back into the project in order for it to work for you. Public Sub UploadFile(ByVal filename As String)
Try
' get the file name from the path
Dim strFile As String = System.IO.Path.GetFileName(filename)
' create an instance of the Web service
Dim svc As New TestUploader.Uploader.FileUploader()
' get the file information for the selected file
Dim fInfo As New FileInfo(filename)
' get the length of the file to see if it is possible
' to upload it (with the standard 4096 kb limit)
Dim numBytes As Long = fInfo.Length
Dim dLen As Double = Convert.ToDouble(fInfo.Length / 1000000)
' look for an overrun on file size
If (dLen < 5) Then
' set up a filestream and binary reader for the file
Dim fStream As New FileStream(filename, FileMode.Open,
FileAccess.Read)
Dim br As New BinaryReader(fStream)
' convert the file to a byte array
Dim data As Byte() = br.ReadBytes(Convert.ToInt32(numBytes))
br.Close()
' pass the byte array and file name to the Web method
Dim sTmp As String = svc.UploadFile(data, strFile)
fStream.Close()
fStream.Dispose()
' this is always OK unless an error occurs
MessageBox.Show("File upload status: " & sTmp, "File Upload")
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Upload Error")
End Try
End Sub
Following the Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles btnBrowse.Click
OpenFileDialog1.Title = "Open File"
OpenFileDialog1.FileName = String.Empty
Try
OpenFileDialog1.InitialDirectory = "C:\Temp"
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Error")
End Try
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName = String.Empty Then
Return
Else
txtFileName.Text = OpenFileDialog1.FileName
End If
End Sub
The class wraps up with the button click event handler for the Upload button. This handler merely checks for text in the file name text box and, if something is there, it sends the value to the Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles btnUpload.Click
If txtFileName.Text <> String.Empty Then
UploadFile(txtFileName.Text)
Else
MessageBox.Show("You must select a file first.", "No File Selected")
End If
End Sub
That wraps up all of the client and server side code necessary to upload any sort of file to a server from a WinForms application. SummaryThis article was intended to demonstrate an easy approach to uploading any sort of a file to a Web Server from a WinForms application. This example uses the default upload size of 4096 KB, if you need to upload larger files, you will need to alter this value by changing the From the web.config file, increasing the upload file size is accomplished in this section of the file: <configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
Visual Basic options:
Set strict="true" to disallow all data type conversions
where data loss can occur.
Set explicit="true" to force declaration of all variables.
-->
<httpRuntime
executionTimeout="110"
maxRequestLength="4096"
/>
|
||||||||||||||||||||||||||||||||||||||||