JQuery插件ajaxfileupload.js异步上传文件实例

在服务器端做文件上传的过程中,如果使用web服务器短端的上传控件去上传文件的话,会导致页面刷新一次,这样对用户的体验就不是很友好了。ajaxfileupload.js是一款jQuery的异步上传文件插件,使用简单且容易上手。

前置条件:ajaxfileupload.js文件,百度下载一个就行。

JS引用:

代码如下:

<script src="/Content/JQueryJS/jquery-2.1.1.js"></script>

<script src="/Content/Js/ajaxfileupload.js"></script>

html代码:

代码如下:

 <input id="fileToUpload" type="file" name="fileToUpload">

JS代码:

代码如下:

function saveCInfo() {

            var filename = document.getElementById("fileToUpload").value;

            if (filename != "") {

                $.ajaxFileUpload({

                    url: '../Order/OrderExec.ashx?oprMode=fileUpload' + "&filename=" + filename + "&billno=" + billno + "&companyname=" + companyname,

                    secureuri: false,

                    fileElementId: 'fileToUpload',//上传控件ID

                    //dataType: 'json',

                    error: function () { alert('error'); },

                    success: function (datax) {

                        if (datax != "") {

                            msgShow('系统提示', '上传成功!', 'info');

                        } else {

                            msgShow('系统提示', '上传失败!', 'info');

                        }

                    }

                });

            } else {

                $.messager.alert('提示', '请选择上传文件', 'info');

            }

        }

后台代码:

代码如下:

public void FileUpload(HttpContext context)

        {

            try

            {

                context.Response.ContentType = "text/html";

                string companyname = context.Request.Params["companyname"];

                string billno = context.Request.Params["billno"];

                string filename = context.Request.Params["filename"];

                string name = companyname + "_" + billno + "_" + filename;

                HttpFileCollection files = HttpContext.Current.Request.Files;

                //指定上传文件在服务器上的保存路径 

                string savePath = context.Server.MapPath("~/upload/");

                //检查服务器上是否存在这个物理路径,如果不存在则创建 

                if (!System.IO.Directory.Exists(savePath))

                {

                    System.IO.Directory.CreateDirectory(savePath);

                }

                savePath = savePath + name;//上传文件路径

                files[0].SaveAs(savePath);//保存文件 

                context.Response.Write(savePath);

            }

            catch (Exception ex)

            {

                context.Response.Write("FileUpload: " + ex.Message);

            }

        }

相关推荐