Amazon Ad

Friday 18 September 2015

How to upload file from jquery ajax

Dear All,

Today I am going to tell you how to upload a file from jquery ajax. First of all you need is a jquery reference and a .cs file as I am doing it in ASP.net.

Step 1 : Create a form, Here I have created a form and included a file upload html <input type="file" id="fileUpload"> and simple button with name "btnUploadFile".

Step 2: Write the javascript code to upload the file

<script type="text/javascript">
            $(document).ready(function () {
                $('#btnUploadFile').on('click', function () {
                    var files = $("#fileUpload").get(0).files;

                    var data = new FormData();
                    data.append('data', files[0]);

                    // Make Ajax request with the contentType = false, and processData = false
                    var ajaxRequest = $.ajax({
                        type: "POST",
                        url: "SendFile.aspx/uploadfile",
                        contentType: false,
                        processData: false,
                        data: data,
                        success: function (data) {
                            alert('File uploaded Successfully');
                        },
                        error: function (xhr, ajaxoptions, thrownerror) {
                            alert(xhr.status);
                            alert(thrownerror);
                        },
                        asyn:false
                        //data: data
                    });
                   
                    ajaxRequest.done(function (xhr, textStatus) {
                        // Do other operation
                    });
                });
            });
</script>

Step 3: Do the code in the .cs file for uploading it on the database and on the server.

Here the uploadfile webmethod will not be called as it is a post request generated from a form and will act like a submit. Below is the page load event in the .cs file
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpPostedFile col=Request.Files[0];
        string extenstion=col.ContentType.Substring(col.ContentType.IndexOf('/')+1);
        string[] allowed = { "pdf", "doc", "docx", "png", "bmp", "jpg", "jpeg" };
        string filename="";
        foreach (string x in allowed)
        {
            if (extenstion.Contains(x))
            {
                filename = Guid.NewGuid().ToString("N") + "." + extenstion;

                //Code here to save the file details in the database
              
                //Save file in the uploads folder
                col.SaveAs(Server.MapPath("~/Uploads")+"/" + filename);
                string t = Request.Url.AbsoluteUri.Substring(0,Request.Url.AbsoluteUri.IndexOf("SendFile"));
                Response.Write(fileid);
                Response.Flush();
                Response.End();
            }
        }

    }

   [WebMethod]
    public static string uploadfile(HttpPostedFile data)
    {
        HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
        return "uploaded";
    }

That's it folks, Hopes it help someone.

2 comments:

Merbin Joe said...

Don't try this, this is not working. It showing error on Page_Load function..

Ritesh said...

Send your code in comment box with the error which you are facing. This is a tested and implemented code and it works in every case.

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...