HTTP File Upload without User Interaction using .NET - Explanation of Code for Upload Function
(Page 3 of 4 )
Let me break up the code for Upload function so that it’s easier to understand.
- First let’s declare the following variables which we would need inorder to implement the upload functionality.
On Error GoTo errhandle
Dim lngFileSize As Long
Dim strData As String
Dim strPostData As String
- Read the size of the file to be uploaded and initialize the labels and progress bar.
'read file length
lngFileSize = FileLen(strFileName)
lngFileLen = lngFileSize
pgUpload.Value = 0
lblFileSize.Caption = lngFileLen
- Next step is to read the file into a string.
Open strFileName For Binary As #2
strData = Input(FileLen(strFileName), #2)
Close #2
- Construct the HTTP Request packet, by first creating the header of the packet giving the protocol being used for sending the request. We will be using POST to send data due to its support of large volume of data. We also specify the content type of the data and what’s the length of the data
strPostData = "POST " & strURL & vbCrLf
strPostData = strPostData & "Content-Type: application/octet-stream" & vbCrLf
strPostData = strPostData & "Content-Length: " & Format$(Len(strData)) & vbCrLf
strPostData = strPostData & "Connection: Keep-Alive" & vbCrLf & vbCrLf
- Complete the HTTP Request packet by appending the data payload.
strPostData = strPostData & strData & vbCrLf
- Now all we need to do is send the Post Data through the Winsock control and complete error handling section
wsUpload.SendData strPostData
UploadFile = True
Exit Function
errhandle:
nErrNo = Err.Number
UploadFile = False
- Copy the following lines of code to implement the progress bar functionality.
'This event is fired once the data has been sent completely
Private Sub wsUpload_SendComplete()
lngTotalBytesSent = 0
lblBytesUploaded.Caption = lngFileLen
pgUpload.Value = 100
End Sub
'This event is fired once the sendData function is called
Private Sub wsUpload_SendProgress(ByVal bytesSent As Long, ByVal bytesRemaining As Long)
Dim nPercent As Integer
lngTotalBytesSent = lngTotalBytesSent + bytesSent
nPercent = Int((lngTotalBytesSent / lngFileLen) * 100)
pgUpload.Value = nPercent
lblBytesUploaded.Caption = lngTotalBytesSent
lblBytesUploaded.Refresh
pgUpload.Refresh
End Sub
7. With the above steps, we have finished the code for uploading the files. Now only the creation of the activex control remains. To create it, click on File menu of VB IDE and there will be a selection called "make fileupload.ocx", click on it and Voila, your activex control is ready.
Next: CAB File >>
More .NET Articles
More By Chandru Prashanth