File Upload Without Using Any Asp Controls

2019-06-09 16:02发布

问题:

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:

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;
            }
        }
    }
}


回答2:

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();
                }
            }
        }
    }


回答3:

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.