tags:

views:

230

answers:

6

I'm trying to make an asynchronous upload operation but I got this error message:

Error occurred, info=An exception occurred during a WebClient request`.

Here's the upload function:

 Private Sub UploadFile()

        Dim uploads As HttpFileCollection
        uploads = HttpContext.Current.Request.Files

        Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
        Dim client = New WebClient

        AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted

        For i As Integer = 0 To (uploads.Count - 1)

            If (uploads(i).ContentLength > 0) Then
                Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)

                Try
                    client.UploadFileAsync(uri, c)
                Catch Exp As Exception

                End Try
                End If
            Next i
          End Sub


 Public Sub UploadFile_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)

        Dim client As WebClient = CType(e.UserState, WebClient)

        If (e.Cancelled) Then
            labMessage.Text = "upload files was cancelled"
        End If

        If Not (e.Error Is Nothing) Then
            labMessage.Text = "Error occured, info=" + e.Error.Message
        Else
            labMessage.Text = "File uploaded successfully"
        End If

    End Sub

Update 1:

Private Sub UploadFile()

    Dim uploads As HttpFileCollection

    Dim fileToUpload = "C:\Demo\dummy.doc"

    Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
    Dim client = New WebClient

    AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted

    client.UploadFileAsync(uri, fileToUpload)


End Sub

client.UploadFileAsync(uri, fileToUpload) is throwing this error message

 Error occured, info=System.Net.WebException: The request was aborted: The request was canceled. at System.Net.FileWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)  
+4  A: 

By calling GetFileName you're truncating whatever path information was there. You should provide UploadFileAsync with a full path name.

Also, replace e.Error.Message with just e.Error so you get the full error details including inner exceptions. This will provide more info and probably lead you to the answer.

Sam
Please see the Update 1
Narazana
A: 

Try this:

1) Create a new class MyWebClient.

Class MyWebClient
  Inherits WebClient

  Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
    Dim req = MyBase.GetWebRequest(address)
    Dim httpReq = TryCast(req, HttpWebRequest)
    If httpReq IsNot Nothing Then
      httpReq.KeepAlive = False
    End If
    Return req
  End Function
End Class

2) Use this class instead of the default WebRequest.

Private Sub UploadFile()

  Dim uploads As HttpFileCollection
  uploads = HttpContext.Current.Request.Files

  Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
  Dim client = New MyWebClient

  AddHandler ...

I hope this helps.

Jan Willem B
Any chance to fix my error in the question?.
Narazana
I changed the code to match your code. Please try the solution and see if it fixes your problem.
Jan Willem B
I got same error as in Update 1.
Narazana
+2  A: 
Dim uri As Uri = New Uri("C:\UploadedUserFiles\") 

The above statement is wrong, how come you have Uri as a file system path, it should be "http://" or "https://" , if you are trying to upload it to your local asp.net web site project then you must have a url something like http://localhost:PORT/UploadedUserFiles ... and you will know port number when you execute project.

Dim uri As Uri = New Uri("http://localhost:PORT/Upload.aspx") 
Akash Kava
I wanted to upload all files to "C:\UploadedUserFiles\" that was why I set uri to that path."UploadedUserFiles" and Web root folder are different location.
Narazana
Well you can only upload to http:// path, however inside Upload.aspx or your page where you are uploading to, you should save the file at c:\uploadeduserfiles location.
Akash Kava
A: 

From the reference to HttpContext.Current.Request.Files I am assuming that your are running the code in a web project. You don't have to use WebClient to save the file to your disk. All you have to do is this:

 Private Sub UploadFile()

    Dim uploads As HttpFileCollection
    uploads = HttpContext.Current.Request.Files

    Dim path As String = "C:\UploadedUserFiles\"

    For i As Integer = 0 To (uploads.Count - 1)

        If (uploads(i).ContentLength > 0) Then
            Dim p As String = System.IO.Path.Combine(path, System.IO.Path.GetFileName(uploads(i).FileName))

            uploads(i).SaveAs(p)
        End If
    Next i
End Sub

I'm not that good with VB.. so there might be syntax problems :) bear with me..

LightX
A: 

You can't upload files from the ASP.NET web request asyncronously via this mechanism. The file is actually in the body of the http request so it is already on the server. Request.Files provides a stream to the files that are already on the server.

You could use something like Silverlight or Flash from the client side.

btlog
A: 

You might want to investigate the AJAX Control Toolkit and use the AsyncFileUpload control.

The control has a server side event when upload is complete. (UploadedComplete) It also has a SaveAs(string filename) method for the uploaded file.

Simple Usage:

Markup

<asp:AsyncFileUpload ID="upload" runat="server" OnUploadedComplete="displayFile"/>

Code Behind

protected void displayFile(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
upload.SaveAs("C:\\text.txt");//server needs permission
}
mikek3332002