Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to Implement uploadify in Asp.net
  • hello.. guys i m trying to Use uploadify in asp.net 3.5 , Can anyone tell me how to Implement the it ..and i also tell me how to pass value of Folder from
    code behind
  • Javascript:


    $(window).load(
    function() {

    $(\"#<%=fileUpload.ClientID %>\").fileUpload({
    'uploader': '<%=uploader %>',
    'buttonImg': '<%=buttonImg %>',
    'cancelImg': '<%=cancelImg %>',
    'folder': '<%=Folder %>',
    'script': '<%=script %>',
    'fileExt': '<%=FileExt %>',
    'fileDesc': '<%=FileDesc %>',
    'sizeLimit': '<%=SizeLimit %>',
    'scriptData': <%=GenerateScriptData() %>,
    'auto': <%=Auto.ToString().ToLower() %>,
    'width': <%=width %>,
    'height': <%=height %>,
    'onSelect': <%=OnSelect %>,
    'onComplete': <%=OnComplete %>,
    'onError': <%=OnUploadError %>,
    'multi': <%=Multi.ToString().ToLower() %>
    });
    }
    );


    ASPX / ASCX:

    <div style=\"float: left;\"><asp:FileUpload ID=\"fileUpload\" runat=\"server\" /></div>


    C# Codebehind:

    #region Private Properties

    string folder = \"\";

    string fileExt = \"\";

    string fileDesc = \"\";

    string sizeLimit = \"2620000\";

    Dictionary<string, string> scriptData;

    bool auto = true;

    string onSelect = \"function(event, queueID, fileObj) { }\";

    string onComplete = \"function(event, queueID, fileObj) { }\";

    string onError = \"function(event, queueID, fileObj, errorObj) { }\";

    bool showSizeLimit = false;

    string sizeLimitClass = \"\";

    bool showPreview = false;

    string previewImage = \"\";

    bool multi = false;

    #endregion

    #region Public Properties

    public string uploader;

    public string buttonImg;

    public string cancelImg;

    public string script = \"\";

    public string Folder { get { return folder; } set { folder = value; } }

    [UrlProperty]
    public string Script { get { return script; } set { script = value; } }

    public string FileExt { get { return fileExt; } set { fileExt = value; } }

    public string FileDesc { get { return fileDesc; } set { fileDesc = value; } }

    public string SizeLimit { get { return sizeLimit; } set { sizeLimit = value; } }

    public Dictionary<string, string> ScriptData
    {
    get { if (scriptData == null) scriptData = new Dictionary<string, string>(); return scriptData; }
    set { scriptData = value; }
    }

    public bool Auto { get { return auto; } set { auto = value; } }

    public string OnSelect { get { return onSelect; } set { onSelect = value; } }

    public string OnComplete { get { return onComplete; } set { onComplete = value; } }

    public string OnUploadError { get { return onError; } set { onError = value; } }

    public int width = 160;

    public int height = 22;

    public string FileUploadID { get { return fileUpload.ClientID; } }

    public bool ShowSizeLimit { get { return showSizeLimit; } set { showSizeLimit = value; } }

    public string SizeLimitClass { get { return sizeLimitClass; } set { sizeLimitClass = value; } }

    public bool ShowPreview { get { return showPreview; } set { showPreview = value; } }

    [UrlProperty]
    public string PreviewImage { get { return previewImage; } set { previewImage = value; } }

    public bool Multi { get { return multi; } set { multi = value; } }

    #endregion

    #region Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
    ClientScriptManager s = this.Page.ClientScript;

    if (!s.IsClientScriptIncludeRegistered(\"LoadUploadify\"))
    s.RegisterClientScriptInclude(\"LoadUploadify\", this.Page.ResolveUrl(\"~/Javascript/jquery.uploadify.js\"));

    if (!IsPostBack)
    {
    uploader = Page.ResolveUrl(\"~/JavaScript/uploader.swf\");

    buttonImg = Page.ResolveUrl(\"~/images/browse3.png\");

    cancelImg = Page.ResolveUrl(\"~/images/cancel.png\");

    script = script == \"\" ? Page.ResolveUrl(\"~/Scripts/upload.ashx\") : Page.ResolveUrl(script);

    plSizeLimit.Visible = showSizeLimit;

    plSizeLimit.CssClass = sizeLimitClass;

    imgPreview.ImageUrl = previewImage;

    hlPreview.Visible = showPreview;
    }
    }

    #endregion

    #region Load Variables

    public void Reload()
    {
    ScriptManager.RegisterStartupScript(this.Page, typeof(Page), \"LoadVars\" + ClientID, \"LoadUploadVariables_\" + ClientID + \"();\", true);
    }

    public string GenerateScriptData()
    {
    string data = \"\";

    if(scriptData != null)
    foreach (KeyValuePair<string, string> kvp in scriptData)
    data += \",'\" + kvp.Key + \"' : '\" + kvp.Value + \"'\";

    data += \",'ClientID':'\" + this.ClientID + \"'\";

    return \"{ \" + data.Substring(1) + \" }\";
    }

    #endregion


    A bit of explaination... I actually have this in a usercontrol (ascx) so i can just pop it in where needed. Something to note tho... you have to be sure if you do an async postback (say, in an updatepanel), that the javascript bit must be called again. So, i have it wrapped in a function and then call it in my Reload function. So, whenever i have a button postback, i just do uploader.Reload(); to re-run the javascript.

    My javascript function is actually below, i cut it out above for simplicity sake:


    $(window).load(
    function() {
    <% if(this.Visible) { %>
    LoadUploadVariables_<%=ClientID %>();
    <% } %>
    }
    );

    function LoadUploadVariables_<%=ClientID %>()
    {
    $(\"#<%=fileUpload.ClientID %>\").fileUpload({
    'uploader': '<%=uploader %>',
    'buttonImg': '<%=buttonImg %>',
    'cancelImg': '<%=cancelImg %>',
    'folder': '<%=Folder %>',
    'script': '<%=script %>',
    'fileExt': '<%=FileExt %>',
    'fileDesc': '<%=FileDesc %>',
    'sizeLimit': '<%=SizeLimit %>',
    'scriptData': <%=GenerateScriptData() %>,
    'auto': <%=Auto.ToString().ToLower() %>,
    'width': <%=width %>,
    'height': <%=height %>,
    'onSelect': <%=OnSelect %>,
    'onComplete': <%=OnComplete %>,
    'onError': <%=OnUploadError %>,
    'multi': <%=Multi.ToString().ToLower() %>
    });
    }


    and then of course, the upload file (which i keep in a Scripts folder off the root) and is a Generic Handler (ashx) file:


    using System;
    using System.Web;
    using System.IO;

    public class Upload : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = \"text/plain\";
    context.Response.Expires = -1;
    System.Drawing.Image original_image = null;

    try
    {
    HttpPostedFile jpeg_image_upload = context.Request.Files[\"Filedata\"];

    try
    {
    // Retrieve the uploaded image
    original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
    }
    catch (Exception ex)
    {

    }

    string savepath = \"\";
    string urlpath = \"~/UploadedFiles/\";

    if (context.Request.QueryString[\"folder\"] != null)
    {
    string tempPath = context.Server.UrlDecode(context.Request.QueryString[\"folder\"]);

    urlpath = tempPath;

    if (!tempPath.StartsWith(\"~\"))
    tempPath = \"~\" + tempPath;

    if (!tempPath.EndsWith(\"/\"))
    tempPath += \"/\";

    savepath = context.Server.MapPath(tempPath);
    }
    else
    savepath = context.Server.MapPath(urlpath);

    string filename = jpeg_image_upload.FileName;

    string tempName = filename;

    int i = 1;

    if (!Directory.Exists(savepath))
    Directory.CreateDirectory(savepath);

    while (File.Exists(savepath + \"/\" + filename))
    {
    string ext = tempName.Substring(tempName.LastIndexOf(\".\") + 1);

    filename = tempName.Substring(0, tempName.LastIndexOf(\".\")) + i + \".\" + ext;

    i++;
    }

    jpeg_image_upload.SaveAs(savepath + @\"\\" + filename);

    context.Response.Write(urlpath + \"/\" + filename);
    context.Response.StatusCode = 200;
    }
    catch (Exception ex)
    {
    context.Response.Write(\"Error: \" + ex.Message);
    }
    }

    public bool IsReusable {
    get {
    return false;
    }
    }

    }


    I will be more than happy to help you if you have any more questions!
  • I am trying but so far without success....

    Could you help me please?

    Thanks Lindsay!
  • I've uploaded a VS2008 C# 3.5 sample for anyone that needs it.

    There's also a VS2005 VB.NET 2.0 sample... forgive my VB, it's not my forte. However, for some reason, I decided to add more comments to the VB version.

    Let me know if you have any questions!


    Edit -- Added VS2005 C# Example
  • Hi,

    I m using MVC and need to implemnet Multiple file uploading as done in uploadify but i m unable to implement it as it is using php and the .net version is for single file upload. Will you please provide an example to how to implemet multiple file upload in MVC


    Thanks,
  • I don't know asp.net. But it is important to note that uploadify is an interface to multiple single uploads. What this means is it manages the queue and releases the queue items individually running the upload script separately for each file to be upload. An array of items is not sent to the upload script only one file. The upload script is run multiple times simultaneously.

    Setting multi to true on Lindsay's code should be all that is needed.
  • Lindsay said:
    I've uploaded a VS2008 C# 3.5 sample for anyone that needs it.

    There's also a VS2005 VB.NET 2.0 sample... forgive my VB, it's not my forte. However, for some reason, I decided to add more comments to the VB version.

    Let me know if you have any questions!




    Hi;

    can you provide me with VS 2005 and C#2.0 example.

    As my whole application is built in it. I tried to convert you application But end up with lots of compilation error.
    So help me out.
  • Hi,

    Here's what I did (c#)

    <%@ WebHandler Language="C#" Class="fileUpload" %>
    using System;
    using System.Web;
    public class fileUpload : IHttpHandler {
    protected System.Web.UI.HtmlControls.HtmlInputFile filMyFile;
    public void ProcessRequest (HttpContext context) {
    if (null != context.Request.Files["Filedata"])
    {
    HttpPostedFile myFile = context.Request.Files["Filedata"];
    int nFileLen = myFile.ContentLength;
    byte[] myData = new byte[nFileLen];
    myFile.InputStream.Read(myData, 0, nFileLen);
    System.IO.FileStream newFile = new System.IO.FileStream(@"YourPath\" + myFile.FileName, System.IO.FileMode.Create);
    newFile.Write(myData, 0, myData.Length);
    newFile.Close();
    }
    }

    public bool IsReusable {
    get {
    return false;
    }
    }

    }


    HTH

    Stan
  • Hello,

    thanks for the great script. Runs perfect.
    For a database-update i need the queueID in uploader.ashx. How i can get it?

    Best regards
  • Here's the VS2005 C# example.
  • I can't found a solution for my problem, but i've use another way to request...
  • What'd you do? curious...
  • I've add the queueID to the folder-path and split the folder-string in uploader.ashx file.
    Not the best way but it works.
  • how do you access the queueID before it's sent? do you change the fileUploadSettings folder value in UploadSelect or something? I wasn't sure how to do this because i'm setting my folder dynamically and the uploadify control does not give me a "getter" function to be able to append anything.
  • The uploader.ashx is called after file complete like in your script.

    $('.uplFileInput1').fileUpload({
    'folder': '199_33488637-fe19-4e8b-9bd2-3098d3932045',
    ...
    });


    ID i need for the database-update
    199

    Folder
    33488637-fe19-4e8b-9bd2-3098d3932045
  • Is it possible to upload the file again for VS2008 C# like you did on May 4, called TestCSharp.zip ?

    Thank you!
  • I don't have it anymore, but I'll work on rewriting it for you! I'll have it for you before the weekend.
  • Nevermind, I found it! and the 2005 version if anyone needs it too.

    Admins, anyway we can get the attachments to not expire this time?

    ** NOTE: This uses the 1.6.2 version of uploadify. The newest will be better, since it has a "getter" function for some of the settings. I just haven't needed to upload anything recently, so I haven't modified the code for the newest version. But hopefully this will give you a good start!
  • Merci Lindsay!! :D

    However, in your code samples (for VS2k8) I can't see a multi variable anywhere? How would I include it and where would I set it??

    Thanks so much
    Gideon
  • If you look at UserControls\SimpleUpload.ascx, you'll see the javascript call to implement the uploader on lines 15-33. All you'd have to do is add a line for multi here.

    function LoadUploadVariables_<%=ClientID %>()
    {
    $("#<%=fileUpload.ClientID %>").fileUpload({
    'uploader': '<%=uploaderSwf %>',
    'buttonImg': '<%=buttonImg %>',
    'cancelImg': '<%=cancelImg %>',
    'folder': '<%=Folder %>',
    'script': '<%=script %>',
    'fileExt': '<%=FileExt %>',
    'fileDesc': '<%=FileDesc %>',
    'sizeLimit': '<%=SizeLimit %>',
    'scriptData': <%=GenerateScriptData() %>,
    'auto': <%=Auto.ToString().ToLower() %>,
    'width': <%=width %>,
    'height': <%=height %>,
    'onSelect': <%=OnSelect %>,
    'onComplete': <%=OnComplete %>,
    'onError': <%=OnUploadError %>,
    'multi': true
    });
    }
  • Dear all,

    Thank you for a great control, and the sample in C#.

    I have s question about your sample: In the control, if I want to upload multi-file and post-back, so how can I get the upload file (because in the SimpleUpload.ascx has only one FileUpload)

    Please help me. Thanks again.
  • Hi All
    First time forum and Uploadify User.

    Even though I've added 'multi': true it still doesn't let me select more than 1 file.
    Is there something else I need to add?
  • sorry my mistake, it's working like a wonder.
  • Hi Lindsay/All

    Your example control in 'TestCsharp' is just great and has given me a very good introduction to the Uploadify.

    If you can take the time out to answer a few questions, I would really appreciate it.

    1. It works fine on IE 32 bit but I've also tried it on 64 bit IE and as there's not a compatible Flash player for this, I can't get it to upload. The file can be selected but not alot more than that. Would you have any ideas as to how I can allow 1 file to be uploaded in this scenario?

    2. Do you plan to update your code to reference the latest versions of the Uploadify and other files? The reason I ask this is that I'm not too sure what's been changed between the versions.

    -----UPDATE----------------
    Has anyone else tried the latest version of uploadify (v2.1.0) in the TestCSharp vs2008 solution? I've given it a go and it doesn't run as smoothly as it did with the older version. I've also updated the .css and .swf but still no joy.
    I would prefer not to use the older version so does anyone have any ideas?
  • Working on a v2.1.0 sample for C#.NET VS2008... will have something for you later today!
  • Hi friends,
    I am using uploadify 2.1.0 to upload the files in my application.Everything works fine in IE ; Firefox shows upload completed in flash but the handler (upload.ashx) which is called to upload the files to server not seems to be working,hence the file wont get upload to the server.Could you please help me out with this issue,its urgent.Please find below my code.


    $(document).ready(function() {
    $("#uploadify").uploadify({
    'uploader': '../UploadifyScripts/uploadify.swf',
    'script': '../UploadifyScripts/upload.ashx',
    'cancelImg': 'Images/cancel.png',
    'buttonImg': 'Images/buttons/browse_btn.gif',
    'fileDesc': 'Image Files',
    'fileExt': '*.jpg;*.jpeg;*.gif',
    'multi': true,
    });
    });
  • How can I use uploadify on post-back?
    I mean without script page. Just like regular asp:FileUpload control.

    Never mind. Found the way around.
  • Thanks Lindsay. I have one question. Can I extend your project to support save the uploaded file to SQL server? If it does, Could you just give me some directions?


    Thanks,Ben
  • Yes, you can do any sort of database manipulation within the Scripts/Upload.ashx file. whatever you write back as your context.Reponse.Write is what is handed to the client side javascript function if you need it there too.
  • Such a damn dirty code Lindsay, but finally could make it to work. thanks.
  • Where can I download the sample uploaded by Lindsay?

    I was wondering how to use this on a form with some textbox controls and the FileUpload control. On click of the button, I would like to first save the form info in database and then save the file to the server, while displaying the progress bar.

    Any suggestions would be appreciated.
  • The user and all related content has been deleted.
  • Well
    I can't get this to work.
    There are some things I just don't get with this
    1. which control/action is posting back
    2. all I see is a FileLoad control, should I see something else
    3. File paths in the script fileload are not relative, they look like this:
    'uploader': '/TestHandler/script/uploadify/uploader.swf',
    'buttonImg': '/TestHandler/script/uploadify/browse3.png',
    'cancelImg': '/TestHandler/script/uploadify/cancel.png',
    'folder': '',
    'script': '/TestHandler/Uploader.ashx',
    so how does a client browser know where to look, the *.png files are not downloaded to internet cache

    Also what are these types in the Page Load event
    plSizeLimit.Visible = showSizeLimit;
    plSizeLimit.CssClass = sizeLimitClass;
    imgPreview.ImageUrl = previewImage;
    hlPreview.Visible = showPreview;

    Lastly, Is there a complete working solution that demonstrates uploadify for asp.net

    regards

    GregJF