• Uploading a file with asp.net, jQuery and jTemplate

    Playing around with jQuery and jTemplate and I had the following problem: On a page created with jTemplate I could not use asp:FileUpload Control. Additionally it would of course be better to have an Ajax / jQuery control as this would better integrate into a jQuery website. There are several jQuery Fileupload controls, and Ajax-Upload is my favorite, e.g. because it allows multiple fileupload and does not require Flash. Andrew Valums, the creator of the Ajax-Upload, has posted a C#-Example but as it’s just posted in the comments it might be missed easily. Additionally I needed it for Visual Basic so I’ve transfered it and wrote this short blog entry.

    First follow the instructions at Ajax-Upload page to setup your page. I use the following JavaScript-Code within my function

    var uploader = new qq.FileUploader({
     element: document.getElementById('file-uploader'),
     action: 'MyWebservice.asmx/ProcessFile',
     debug: false,
     sizeLimit: 1100000, // max size 1 MB 
     allowedExtensions: ['txt']
    });

    In the webservice I then use the following code. The code is shortened to the basics, of course you should add a check whether the filename already exists etc. but it should only demonstrate how to save the uploaded file.

    Dim Filename As String = "c:\temp\upload.txt"
    'get reference to posted file and do what you want with this file 
    If Me.Context.Request.Files.Count = 0 Then
     'Firefox does not upload it as file 
     Dim Length As Integer = 4096 
     Dim BytesRead As Integer = 0 
     Dim buffer As [Byte]() = New [Byte](Length) {} 
     Try
     Using fileStream As New IO.FileStream(ImportPath & Filename, IO.FileMode.Create)
     Do
     BytesRead = Context.Request.InputStream.Read(buffer, 0, Length)
     fileStream.Write(buffer, 0, BytesRead)
     Loop While BytesRead > 0
     End Using
     Catch ex As UnauthorizedAccessException
     ' log error hinting to set the write permission of ASPNET or the identity accessing the code
     End Try
    Else
     Dim postedfile As HttpPostedFile
     postedfile = TryCast(Me.Context.Request.Files.[Get](0), HttpPostedFile)
     postedfile.SaveAs(Filename)
    End If

    That’s it.  Tested with IE 8 and Firefox 3.6.

Leave a comment

If you want to share your opinion, leave a comment.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">