jQWidgets Forums
jQuery UI Widgets › Forums › Editors › FileUpload › How to use jqxFileUpload in ASP.NET › Reply To: How to use jqxFileUpload in ASP.NET
Hi guys. Well, thanks for all the useful code. Here is an example of using jqxFileUpload with ASP.NET in C#.
First create a WebService asmx. For this example, It’s called UploadFiles.asmx and the WebMethod is called Upload().
Do note that in my web application I am setting an ID for each user, and storing it in a session variable. I wanted to create a folder for individual users, based on that ID, and upload their own files there:
Client Code:
(JQuery)
$("#jqxFileUpload").jqxFileUpload({ browseTemplate: 'success',
uploadTemplate: 'primary',
cancelTemplate: 'danger',
width: 300,
uploadUrl: 'UploadFiles.asmx/Upload',
fileInputName: 'fileToUpload'
});
$('#jqxFileUpload').on('uploadEnd', function (event) {
var args = event.args;
var fileName = args.file;
var serverResponse = args.response;
$("#spnResponse").html(serverResponse);
});
(HTML)
<div id="jqxFileUpload"></div><br /><br />
<span id="spnResponse"></span>
Server-Side Code:
(UploadFiles.asmx)
<%@ WebService Language=”C#” CodeBehind=”~/App_Code/UploadFiles.cs” Class=”UploadFiles” %>
(UploadFiles.cs)
....
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UploadFiles : System.Web.Services.WebService {
public UploadFiles () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(EnableSession = true)]
public string Upload() {
string appid = HttpContext.Current.Session["appid"].ToString();
string returnTxt;
if (!System.IO.Directory.Exists(Server.MapPath(@"~/uploads/" + appid)))
{
System.IO.Directory.CreateDirectory(Server.MapPath(@"~/uploads/" + appid));
}
string filepath = Server.MapPath("~/uploads/" + appid);
HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files;
returnTxt = string.Empty;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
try
{
if (userPostedFile.ContentLength > 0)
{
returnTxt += "<u>File #" + (i + 1) + "</u><br>";
returnTxt += "File Content Type: " + userPostedFile.ContentType + "<br>";
returnTxt += "File Size: " + userPostedFile.ContentLength + "kb<br>";
returnTxt += "File Name: " + userPostedFile.FileName + "<br>";
userPostedFile.SaveAs(filepath + "\\" + Path.GetFileName(userPostedFile.FileName));
returnTxt += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>";
}
}
catch (Exception Ex)
{
returnTxt += "Error: <br>" + Ex.Message;
}
}
return returnTxt;
}
}
Hope this is useful for somebody.
Regards,
AJ