Results 1 to 8 of 8

Thread: File upload through Ajax

  1. #1

    Thread Starter
    Member
    Join Date
    Jul 2007
    Posts
    36

    File upload through Ajax

    Folks,

    I'm going through tutorials about uploading file through Ajax. This one, this one, and another one. They are very similar. Both stuff the data into an object and post it with $.ajax(...) . So far so good.

    There is a line
    Code:
    m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);
    What is the first [0] for? Why is it required? Where can I read more about the files[] array?

    Any suggestion, insight or reference is really appreciated!

    Best,
    -Nick

  2. #2
    Frenzied Member tr333's Avatar
    Join Date
    Nov 2004
    Location
    /dev/st0
    Posts
    1,606

    Re: File upload through Ajax

    Some useful links for reading:

    https://developer.mozilla.org/en-US/...b_applications
    https://developer.mozilla.org/en-US/docs/Web/API/File
    https://developer.mozilla.org/en-US/...b/API/FileList

    In short, you are selecting the file input on name attribute, not id. Multiple elements on a page can share the same name attribute, so you have [0] to select the first one in the list returned by the jQuery selector.

    Each file input element can select multiple files for upload with the multiple attribute, hence having a files property instead of just singular file.
    CSS layout comes in to the 21st century with flexbox!
    Just another Perl hacker,

  3. #3
    New Member
    Join Date
    May 2015
    Posts
    6

    Re: File upload through Ajax

    hi,
    refer following web site as what your requirement its clear picture up on solve it
    http://www.sanwebe.com/2014/04/ajax-...ent-jquery-php
    http://blogs.html5andcss3.org/php-se...th-attachment/

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882

    Re: File upload through Ajax

    Here's how I do ajax-like uploads in an inner FORM/IFRAME

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head id="Head1" runat="server">
            <title></title>
            <link href="../css/AWCOffice.css"rel="stylesheet" type="text/css" />
            <link href="../css/Final.css" rel="stylesheet" type="text/css" />
        </head>
        <body>
            <form id="form1" onsubmit="return false;" runat="server">
                <div id="acs-edit-bidsbid" style="padding-left: 10px; padding-top: 10px;">
    .
    .
    .        Step #1 - Browse for file to upload and click Upload button
            <span class="acs-span-large">Upload Key</span>
            <label class="awc-UpId awc-ctrlval1 acs-edit-small-text"></label>
            <br />
            <br />
            <form action="Upload.ashx" method="post" enctype="multipart/form-data" target="upload_target_view1">
                <div>
                    <label>
                        <input type="file" name="file" multiple>
                    </label>
                    <br /><br />
                    <button type="submit" name="username" value="(awc_UploadCreate_Bid)" class="ui-button ui-widget ui-state-highlight ui-corner-all ui-button-text-icon-acs-use ui-button-text-icon-primary" role="button" aria-disabled="false">Upload</button>
                </div>
                <iframe name="upload_target_view1" class="acs-dlg-upload">
                    <html>
                        <head></head>
                        <body></body>
                    </html>
                </iframe>
            </form>
            <ul id="filelist">
            </ul>
            <br />
    Then using jQuery I "find" that DIV with the CSS "acs-dlg-upload"

    Code:
    wesUP = wesEP.find(".acs-dlg-upload");
    
    if (wesUP.length != 0) {
        wesUPS = wesUP.siblings().find("button:submit");
        strUPS = wesUPS.attr("value") || "";
        strUPS = (window.username || "") + strUPS;
        wesUPS.attr("value", strUPS)
        wesUP.load(function () {
            var strResult = wesUP.contents().find("body").html();
            if (strResult.length != 0) {
                uploadComplete(strEditPanel, strResult);
            }
            return false;
        });
    }
    That wires up the uploadComplete function for the LOAD event of the IFRAME

    Code:
    function uploadComplete(strId, strResult) {
        var returnObj = $.parseJSON(strResult);
        var updArr = returnObj.update || [];
        var strData = "";
        var wesAWC = [];
        for (var i = 0; i < updArr.length; i = i + 2) {
            strData = updArr[i + 1];
            wesAWC = $(strId + " .awc-" + updArr[i]).not(".acs-edit-view-hidden");
            p_fillField(wesAWC, strData, strId, updArr[i], false);
        }
        if (returnObj.ok) {
            errorMessage("Upload Complete", returnObj.message);
        } else {
            errorMessage("Upload DID NOT Complete", returnObj.message);
        }
        return false;
    }
    And the FORM talks to an upload page - indicated in this line of the HTML

    <form action="Upload.ashx" method="post" enctype="multipart/form-data" target="upload_target_view1">

    And that page - in VB.Net - looks like this

    Code:
    <%@ WebHandler Language="VB" Class="Upload" %>
    
    Imports System
    Imports System.Web
    Imports System.IO
    Imports System.Data
    Imports System.Data.SqlClient
    
    Public Class Upload : Implements IHttpHandler
        
        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim username As String = context.Request.Params("username")
            Dim credDB As String = ""
            Dim overSproc As String = ""
            If username.EndsWith(")") Then
                Dim cp As Integer = username.LastIndexOf("(")
                overSproc = username.Substring(cp + 1, username.Length - cp - 2)
                username = username.Substring(0, cp)
            End If
            If username.Contains(":") Then
                credDB = username.Split(":"c)(0)
                username = username.Split(":"c)(1)
            End If
    
            Dim postedFile As HttpPostedFile = context.Request.Files("file")
    which finishes up like this

    Code:
                        postedFile.SaveAs(Path.Combine(savepath, StoredFileName))
                        strResp &= "{ ""ok"": true"
                        strResp &= ", ""message"": """ & Message & """"
                        strResp &= ", ""update"": " & Update
                        strResp &= "}"
                        context.Response.Write(strResp) 'filename)
                        context.Response.StatusCode = 200
                    End If
                End If
            Catch ex As Exception
                strResp = "{""ok"": false, ""message"": ""Error: " & ex.Message.Replace("""", "'").Replace("\", "\\") & ".""}"
                context.Response.Write(strResp) 'filename)
                context.Response.StatusCode = 200
            End Try
        End Sub
     
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
    
    End Class

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  5. #5
    Banned
    Join Date
    Jul 2015
    Posts
    15

    Thumbs up Re: File upload through Ajax

    File upload through Ajax

    //form html
    <p id="status"></p>
    <form id="form1" enctype="multipart/formdata">
    <input type="file" id="photo" name="photo" />
    <input type="submit" id="save" name="save" value="Upload" />
    </form>
    //php file

    if($_POST){
    $name = $_POST['photo']['name'];
    $tmp = $_POST['photo']['tmp_name'];
    $path = "images/".basename(name);
    if(move_uploaded_file($tmp,$path)){
    print("Done! File saved...");
    }else{
    die("Error on uploading!")
    }
    }
    //js
    $(document).ready(function(){
    var photo = $("#photo").val();
    $.post("upload.php",{photohoto},function(data){
    $("#status").html(data);
    });
    });

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882

    Re: File upload through Ajax

    @beingchinmay - I'm curious - does that refresh the page that requested the upload?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7
    Banned
    Join Date
    Jul 2015
    Posts
    15

    Thumbs up Re: File upload through Ajax

    No sir

  8. #8
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    17,882

    Re: File upload through Ajax

    Yes - I see that now that I look closely.

    Your example is the main form in the page though - right? My example is in an iframe.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width