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
1 var uploader = new qq.FileUploader({ 2 element: document.getElementById('file-uploader'), 3 action: 'MyWebservice.asmx/ProcessFile', 4 debug: false, 5 sizeLimit: 1100000, // max size 1 MB 6 allowedExtensions: ['txt'] 7 });
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.
1 Dim Filename As String = "c:\temp\upload.txt" 2 'get reference to posted file and do what you want with this file 3 If Me.Context.Request.Files.Count = 0 Then 4 'Firefox does not upload it as file 5 Dim Length As Integer = 4096 6 Dim BytesRead As Integer = 0 7 Dim buffer As [Byte]() = New [Byte](Length) {} 8 Try 9 Using fileStream As New IO.FileStream(ImportPath & Filename, IO.FileMode.Create) 10 Do 11 BytesRead = Context.Request.InputStream.Read(buffer, 0, Length) 12 fileStream.Write(buffer, 0, BytesRead) 13 Loop While BytesRead > 0 14 End Using 15 Catch ex As UnauthorizedAccessException 16 ' log error hinting to set the write permission of ASPNET or the identity accessing the code 17 End Try 18 Else 19 Dim postedfile As HttpPostedFile 20 postedfile = TryCast(Me.Context.Request.Files.[Get](0), HttpPostedFile) 21 postedfile.SaveAs(Filename) 22 End If
That’s it. Tested with IE 8 and Firefox 3.6.
no comment untill now