文件上传不使用任何Asp控件

本文关键字:任何 Asp 控件 文件 | 更新日期: 2023-09-27 17:53:55

我试图在不使用任何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页面和在UploadPhoto()方法在JQuery:

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

我正在发布c#代码后面。但是,我无法从后台代码访问上传的项目。

        [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;
        }
然而

请求。Files似乎是一个空数组。由于方法是静态的([WebMethod]),我无法到达方法内的输入控件来获取发布的文件。我该如何克服这个问题?谢谢你。

文件上传不使用任何Asp控件

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

请从下方链接下载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;
            }
        }
    }
}

是的,您可以通过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();
                }
            }
        }
    }

为什么不使用默认的asp控件?最好使用. net框架提供的默认控件。使用默认控件将删除长期运行中出现的任何依赖项。

相关文章: