0

I'm trying to upload an image without using any of the asp controls. So far I've been trying:

        <form id="form1" data-ajax="false" method="post" runat="server" enctype="multipart/form-data">
            <input type="file" id="uploadFile" name="uploadFile" runat="server"/>
            <input type="submit" class="btn-login" data-corners="true" value="Yükle" onclick="UploadPhoto()" />
        </form>

in my .aspx page and in UploadPhoto() method in JQuery:

function UploadPhoto() {
            $.ajax({
                type: "POST",
                url: "IncidentChange.aspx/UploadPhoto",
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                },
                error: function () {
                }
            });
        }

I am posting to C# code behind. However, I could not reach the uploaded item from codebehind.

        [WebMethod]
        public static string UploadPhoto()
        {
            try
            {
                byte[] fileData = null;
                using (var binaryReader = new BinaryReader(HttpContext.Current.Request.Files[0].InputStream))
                {
                    fileData = binaryReader.ReadBytes(HttpContext.Current.Request.Files[0].ContentLength);
                }

            }
            catch (Exception ex)
            {
            }
            return null;
        }

However Request.Files appears to be a null array. Since the method is static ([WebMethod]) I cannot reach the input control within the method to get the posted file. How can I overcome this issue? Thank you.

1
  • your are not sending the file in the ajax data Commented Mar 26, 2014 at 8:53

3 Answers 3

2

Html:

<input type="file" id="uploadFile" name="uploadFile"/>
<input type="button" id="submit" value="Submit" onClick="UploadFile();"/> 

JQuery:

 <script type="text/javascript">
$(document).ready(function () {
        function UploadFile() {
    var fileName = $('#uploadFile').val().replace(/.*(\/|\\)/, '');
                       if (fileName != "") {
                        $.ajaxFileUpload({ url: 'AjaxFileUploader.ashx',
                            secureuri: false,
                            fileElementId: 'uploadFile',
                            dataType: 'json',
                            success: function (data, status) {
                               if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            alert('Success');
                        }
                    }
                },
                  error: function (data, status, e) {
                                alert(e);
                            }
                        }
                        )
                    }
}
});

Please download ajax file uploader plugin from tyhe bekow link.

http://www.phpletter.com/DOWNLOAD/

Handler:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Text;
 namespace MyProject
 {
   public class AjaxFileUploader : IHttpHandler
   {
    {

        public void ProcessRequest(HttpContext context)
        {

            if (context.Request.Files.Count > 0)
            {
                string path = context.Server.MapPath("~/UploadImages");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var file = context.Request.Files[0];

                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = file.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = file.FileName;
                }
                string newFilename = Guid.NewGuid().ToString();
                FileInfo fInfo = new FileInfo(fileName);
                newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension);
                string strFileName = newFilename;
                fileName = Path.Combine(path, newFilename);
                file.SaveAs(fileName);


                string msg = "{";
                msg += string.Format("error:'{0}',\n", string.Empty);
                msg += string.Format("msg:'{0}'\n", strFileName);
                msg += "}";
                context.Response.Write(msg);


            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

I couldn't get your code to work. I cannot Post the file to the .ashx
Thank you, I appreciate it, but still it doesn't postback. Are you sure <%@ WebHandler Language="C#" Class="AjaxFileUploader" %> line should be in .ashx.cs file? It doesn't even compile that way.
@HasanCanSaral, There is no .ashx.cs file. Only .ashx file only. No code behind file. i.e Generic Handler
We are referring to the same thing I guess, there is no such thing as .ashx. Generic Handler only comes as .ashx.cs in Visual Studio and it doesn't compile with that line, nor does the method get fired.
@HasanCanSaral, Thank you man. I have added that namespace now in handler file.
|
1

Yes you can achive this by ajax post method. on server side you can use httphandler.

with ajax you can show the upload progress also.

you will have to read the file as a inputstream.

using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName))
    {
        Byte[] buffer = new Byte[32 * 1024];
        int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        while (read > 0)
        {
            fs.Write(buffer, 0, read);
            read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        }
    } 

Sample Code

function sendFile(file) {              
        debugger;
        $.ajax({
            url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data
            type: 'POST',
            xhr: function () {
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: function (result) {                    
                //On success if you want to perform some tasks.
            },
            data: file,
            cache: false,
            contentType: false,
            processData: false
        });
        function progressHandlingFunction(e) {
            if (e.lengthComputable) {
                var s = parseInt((e.loaded / e.total) * 100);
                $("#progress" + currFile).text(s + "%");
                $("#progbarWidth" + currFile).width(s + "%");
                if (s == 100) {
                    triggerNextFileUpload();
                }
            }
        }
    }

Comments

0

why you are not using the default asp controls??It is good to use the default controls provided by the .Net frame work.Using the default controls will remove any dependencies that will come in long run.

2 Comments

It's an HTML5 project ,for mobile. No asp tags, it's a customer requirement.
Plus, this doesn't help in any way. I would downvote your answer if I could.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.