不使用任何Asp控件的文件上载

时间:2014-03-26 08:48:49

标签: c# jquery asp.net ajax file-upload

我试图在不使用任何asp控件的情况下上传图片。到目前为止,我一直在尝试:

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

在我的.aspx页面和JQuery中的UploadPhoto()方法中:

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

我发布了C#代码。但是,我无法从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;
        }

但是Request.Files似乎是一个空数组。由于该方法是静态的([WebMethod]),我无法在方法中到达输入控件来获取发布的文件。我怎样才能克服这个问题?谢谢。

3 个答案:

答案 0 :(得分: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);
                            }
                        }
                        )
                    }
}
});

请从tyhe bekow链接下载ajax文件上传器插件。

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

处理程序:

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

答案 1 :(得分:1)

是的,你可以通过ajax post方法实现这个目标。在服务器端,您可以使用httphandler。

使用ajax,您也可以显示上传进度。

您必须将文件作为输入流读取。

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

示例代码

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

答案 2 :(得分:0)

为什么你没有使用默认的asp控件?最好使用.Net框架工作提供的默认控件。使用默认控件将删除任何长期运行的依赖项。