GVKun编程网logo

asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?(contextclick)

14

在本文中,我们将带你了解asp.net–如何将ContextKeys属性用于AjaxFileUpload控件?在这篇文章中,我们将为您详细介绍asp.net–如何将ContextKeys属性用于Aja

在本文中,我们将带你了解asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?在这篇文章中,我们将为您详细介绍asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?的方方面面,并解答contextclick常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的$.ajaxFileUpload、$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、.net mvc ajaxfileupload.js 上传文件、.Net MVC 用 ajaxfileupload 上传图片

本文目录一览:

asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?(contextclick)

asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?(contextclick)

我开始查看AjaxFileUpload控件,特别是ContextKeys属性.但是,我不明白如何使用它.

The documentation对AjaxFileUpload说,ContextKeys用于在上传文件时将信息传递给服务器.但没有提供任何例子.我在网上有任何可以看的例子吗?

解决方法

虽然没有实现这样的功能(我相信它是有计划的,但由于某些原因被推迟),但没有什么可以保护你自己实现它.为此,您需要下载AjaxControlToolkit源代码并根据您的需要进行调整.

会有很多积分,所以你可以准备一杯咖啡:)

我将显示必须更改的文件名的更改.

Server / AjaxControlToolkit / AjaxFileUpload / AjaxFileUpload.cs文件

首先,将ContextKeys属性添加到AjaxFileUploadEventArgs.cs文件(它位于同一文件夹中):

/// <summary>
/// Gets or sets the context keys.
/// </summary>
public string ContextKeys
{
    get;
    set;
}

之后打开AjaxFileUpload类代码并更改OnPreRender方法.以下是此方法的一部分,包含自定义修改:

var eventArgs = new AjaxFileUploadEventArgs(guid,AjaxFileUploadState.Success,"Success",uploadedFile.FileName,uploadedFile.ContentLength,uploadedFile.ContentType,stream.ToArray());

// NEW CODE HERE
eventArgs.ContextKeys = this.Page.Request.Form["contextKeys"];

这就是我们需要的服务器代码的所有变化.现在我们需要修改Sys.Extended.UI.AjaxFileUpload客户端类(文件AjaxFileUpload.pre.js)

首先让我们修改_html5UploadFile方法如下:

_html5UploadFile: function (fileItem) {
    this._guid = Sys.Extended.UI.AjaxFileUpload.utils.generateGuid();

    var uploadableFile = fileItem.get_fileInputElement();

    var fd = new FormData();
    fd.append("fileId",uploadableFile.id);
    fd.append("Filedata",uploadableFile.file);

    if (this.contextKeys) {
        if (typeof this.contextKeys !== "string") {
            this.contextKeys = Sys.Serialization.JavaScriptSerializer.serialize(this.contextKeys);
        }
        fd.append("contextKeys",this.contextKeys);
    }

    $common.setVisible(this._progressBar,true);
    this._setdisableControls(true);
    this._html5SetPercent(0);
    this._setStatusMessage(String.format(Sys.Extended.UI.Resources.AjaxFileUpload_UploadingHtml5File,uploadableFile.file.name,Sys.Extended.UI.AjaxFileUpload.utils.sizetoString(uploadableFile.file.size)));

    var url = this._postBackUrl;
    if (url.indexOf("?") != -1)
        url += "&";
    else
        url += "?";

    this._webRequest = new Sys.Net.WebRequest();
    this._executor = new Sys.Net.XMLHttpExecutor();
    this._webRequest.set_url(url + 'contextkey=' + this._contextKey + '&guid=' + this._guid);
    this._webRequest.set_httpVerb("POST");
    this._webRequest.add_completed(this.bind(this._html5OnRequestCompleted,this));

    //this._executor.add_load(this.bind(this._html5OnComplete,this));
    this._executor.add_progress(this.bind(this._html5OnProgress,this));
    this._executor.add_uploadAbort(this.bind(this._html5OnAbort,this));
    this._executor.add_error(this.bind(this._html5OnError,this));
    this._webRequest.set_executor(this._executor);

    this._executor.executeRequest(fd);
}

如您所见,我们将contextKeys添加到表单数据中,并使用Ajax请求发布.

我们需要修改_uploadInputElement方法:

_uploadInputElement: function (fileItem) {

    var inputElement = fileItem.get_fileInputElement();
    var uploader = this;
    uploader._guid = Sys.Extended.UI.AjaxFileUpload.utils.generateGuid();
    setTimeout(function () {
        uploader._setStatusMessage(String.format(Sys.Extended.UI.Resources.AjaxFileUpload_UploadingInputFile,Sys.Extended.UI.AjaxFileUpload.utils.getFileName(inputElement.value)));
        uploader._setdisableControls(true);
        uploader.setThrobber(true);
    },0);

    var url = uploader._postBackUrl;
    if (url.indexOf("?") != -1)
        url += "&";
    else
        url += "?";

    uploader._createVForm();
    uploader._vForm.appendChild(inputElement);

    if (this.contextKeys) {
        if (typeof this.contextKeys !== "string") {
            this.contextKeys = Sys.Serialization.JavaScriptSerializer.serialize(this.contextKeys);
        }

        var contextKeysInput = document.createElement("input");
        contextKeysInput.setAttribute("type","hidden");
        contextKeysInput.setAttribute("name","contextKeys");
        contextKeysInput.setAttribute("value",this.contextKeys);

        uploader._vForm.appendChild(contextKeysInput);
    }

    uploader._vForm.action = url + 'contextkey=' + this._contextKey + '&guid=' + this._guid;
    uploader._vForm.target = uploader._iframeName;

    setTimeout(function () {
        uploader._vForm.submit();
        uploader._waitTimer = setTimeout(function () { uploader._wait() },100);
    },0);
}

完成所有这些更改后,您可以在代码隐藏中设置ContextKeys属性,并从UploadComplete事件的AjaxFileUploadEventArgs参数中获取它,如下所示:

protected void Page_Load(object sender,EventArgs e)
{

    if (!IsPostBack && !AjaxFileUpload1.IsInFileUploadPostBack)
    {
        AjaxFileUpload1.ContextKeys = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new Dictionary<string,string> { { "1","First" },{ "2","Second" } });
    }

protected void AjaxFileUpload1_OnUploadComplete(object sender,AjaxFileUploadEventArgs file)
{
    if (!string.IsNullOrEmpty(file.ContextKeys))
    {
        var contextKeys = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string,string>>(file.ContextKeys);
    }

此外,如果您将实现此处建议的OnClientUploadStarted客户端事件link,您可以从客户端传递给服务器您的contextKeys:

function uploadStarted(sender,args) {
      sender.contextKeys = { "first": "1","second": "2" };
 }

$.ajaxFileUpload

$.ajaxFileUpload

我用的是这个:https://github.com/carlcarl/AjaxFileUpload

下载地址在这里:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar

AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

当初做了个异步上传的功能,选择它因为它的配置方式比较像jQuery的AJAX,我很喜欢。

ajaxFileUpload是一个异步上传文件的jQuery插件 语法:$.ajaxFileUpload([options])

options参数说明:

1、url           上传处理程序地址。 2,fileElementId      需要上传的文件域的ID,即“<input type="file">”的ID。 3,secureuri        是否启用安全提交,默认为false。 4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。 5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。 6,error          提交失败自动执行的处理函数。 7,data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。 8, type           当要提交自定义参数时,这个参数要设置成post

使用方法: 1.引入ajaxfileupload.js 2.在HTML中写出

<input id="fileInput" type="file" name="file"/>

3.在js中使用$.ajaxFileUpload

// 上传
		$.ajaxFileUpload({
			url : ctx + ''calculate/upload'',
			secureuri : false,
			fileElementId : ''fileInput'',
			dataType : ''json'',
			success : function(data, status) {
				$("#progressbar").progressbar("value", 100);
				$("#download_div").show();
			},
			error : function(data, status) {
				$("#progressbar").hide();
				alert("上传文件错误");
			}
		});

4.在controller中接收

public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model)

这样接收的file就是上传的文件了

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错,这是什么原因?

.net mvc ajaxfileupload.js 上传文件

.net mvc ajaxfileupload.js 上传文件

网上搜的类似资料一大堆,能用没几个。这个是自己工作中用到的,特此记录。
(

本文章以下Js方法需要自己改写, 或者注释掉, 或者使用Console.log() 来查看执行步骤,
Loading(true, "拼命导入中..请稍后...");
$.download("../../TicketManage/SendGoods/DownLoadTemplate", ''post'');
dialogMsg(e, -1);
)
Util.Offices.ExcelHelper.ExcelToDt(stream); 使用Epplus把流转换成DataTable(代码下面贴出了)

----------------------------------------------------------------------------不华丽的代码分割线------------------------------------------------------------------------------------------

uploadForm.cshtml

 

@{
    ViewBag.Title = "数据导入";
    Layout = "~/Views/Shared/_Index.cshtml";
}
<script src="~/Content/scripts/plugins/ajaxfileupload/ajaxfileupload.js"></script>
<script>

    $(function () {
        $(''#uploadFile'').bind("change", function (e) {
            //alert("a");
        });
    });

    //开始导入
    function btn_importdata() {
        Loading(true, "拼命导入中..请稍后...");
        $.ajaxFileUpload({
            url: ''../../TicketManage/SendGoods/Import'',//后台请求地址
            type: ''POST'',//请求方式  当要提交自定义参数时,这个参数要设置成post
            secureuri: false,//是否启用安全提交,默认为false。
            fileElementId: ''uploadFile'',// 需要上传的文件域的ID,即<input type="file">的ID。
            dataType: ''json'',
            success: function (data) {//提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
                $("#msg").html("");
                var d = data.msg.split(''\n'');
                if (data.state) {
                    $("#msg").attr("class", "alert alert-success").append(data.msg);
                } else {
                    $("#msg").attr("class", "alert alert-danger");
                    for (var i = 0; i < d.length; i++) {
                        if (+d[i] != '''') {
                            $("#msg").append("<strong>警告!</strong>" + d[i] + "<br/>");
                        }
                    }
                }
                $("#uploadFile").val('''');//解决同名文件只发送一次请求的问题
                $("#filetext").val('''');//友好提示文件名
                Loading(false);
            },
            error: function (json, status, e) {//提交失败自动执行的处理函数。
                dialogMsg(e, -1);
                $("#msg").html(e);
                // console.log(data);
                $("#uploadFile").val('''');//解决同名文件只发送一次请求的问题
                $("#filetext").val('''');//友好提示
                Loading(false);
            }
        });
    }
    //设置显示
    function onchange_ShowFile(e) {
        var file = $("#uploadFile").val();
        //var pos = file.lastIndexOf("\\");
        //console.log(file);
        $("#filetext").val(file);
        //console.log(file.substring(pos + 1));
    }
    //选择文件
    function btn_getimportdata() {
        $("#uploadFile").trigger(''click'');
    }
    //下载模板
    function btn_downLoadTempte() {
        $.download("../../TicketManage/SendGoods/DownLoadTemplate", ''post'');
    }
</script>

<div>
    <div>
        <div>
            <input id="uploadFile" name="uploadFile" onchange="onchange_ShowFile()"type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
            <input readonly type="text"id="filetext" />
            <button id="choose"onclick="btn_getimportdata()"> <i></i> 选择</button>
            <button id="lr-choose"onclick="btn_importdata()"><i></i> 开始导入</button>
            <button id="lr-import"onclick="btn_downLoadTempte()">  <i></i> 下载模板</button>
        </div>
        <div id="tips">
            <strong> 提示:</strong>1.下载模板文件并将相关数据正确填充  2.点击选择文件。3.点击开始导入。4.返回结果
        </div>

        <divid="msg">
            <strong>返回结果:</strong>在这里看返回结果哦<br />
        </div>
    </div>
</div>

  

后台代码:

#region 导入数据
        [HttpPost]
        public ActionResult Import()
        {
            var files = Request.Files;
            JsonResult json = new JsonResult
            {
                ContentType = "text/html",
            };

            var currentUser = OperatorProvider.Provider.Current();

            if (files.Count > 0)
            {
                var stream = files[0].InputStream;
                var name = files[0].FileName;
                if (name.IsEmpty())
                {
                    json.Data = new { state = false, msg = "请先选择文件" }; return json;
                }
                if (name.Length <= 4)
                {
                    json.Data = new { state = false, msg = "文件格式不正确" }; return json;
                }
                if (name.Substring(name.Length - 4).ToUpper() != "XLSX")
                {
                    json.Data = new { state = false, msg = "文件格式不正确,请使用xlsx文件" }; return json;
                }
                var dt = Util.Offices.ExcelHelper.ExcelToDt(stream);

                List<DataRow> removelist = new List<DataRow>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool IsNull = true;
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                        {
                            IsNull = false;
                        }
                    }
                    if (IsNull)
                    {
                        removelist.Add(dt.Rows[i]);
                    }
                }
                for (int i = 0; i < removelist.Count; i++)
                {
                    dt.Rows.Remove(removelist[i]);
                }
                if (dt.Rows.Count == 0)
                {
                    json.Data = new { state = false, msg = "文件中无数据,请重新上传。" }; return json;
                }
                var res = sendgoodsbll.Import(dt);
                json.Data = new { state = res.Item1, msg = res.Item2 };
                return json;
            }
            else
            {
                json.Data = new { state = false, msg = "上传失败,无文件" }; return json;
            }
        }
        [HttpPost]
        public void DownLoadTemplate()
        {
            var fileName = Server.MapPath("~/Resource/Template/导入终端发货单模板.xlsx");
            FileHelper.DownLoadold(fileName, "导入终端发货单模板.xlsx");
        }
        #endregion

  

把文件流转换成DataTable帮助类:

 

public static DataTable ExcelToDt(Stream stream)
        {

            ExcelPackage package = new ExcelPackage(stream);
            ExcelWorksheet sheet = package.Workbook.Worksheets[1];

            DataTable dt = new DataTable();
            //for (int col = 0; col < sheet.Dimension.End.Column; col++)
            //{
            //    dt.Columns.Add(col.ToString(), );
            //}
            foreach (var firstRowCell in sheet.Cells[1, 1, 1, sheet.Dimension.End.Column])
            {
                dt.Columns.Add(firstRowCell.Text, Type.GetType("System.String"));
            }
            int startRowIndx = sheet.Dimension.Start.Row + 1;//去掉列头
            for (int r = startRowIndx; r <= sheet.Dimension.End.Row; r++)
            {
                DataRow dr = dt.NewRow();
                for (int c = sheet.Dimension.Start.Column; c <= sheet.Dimension.End.Column; c++)
                {
                    if (sheet.Cells[r, c].Style.Numberformat.Format.IndexOf("yyyy") > -1
                        && sheet.Cells[r, c].Value != null)//注意这里,是处理日期时间格式的关键代码
                    {

                        dr[c - 1] = sheet.Cells[r, c].GetValue<DateTime>();
                    }
                    else
                        dr[c - 1] = (sheet.Cells[r, c].Value ?? DBNull.Value)?.ToString()?.Trim();
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

  

本人修改后的ajaxfileupload.js文件

 

jQuery.extend({


    createUploadIframe: function (id, uri) {
        //create frame
        var frameId = ''jUploadFrame'' + id;
        var iframeHtml = ''<iframe id="'' + frameId + ''" name="'' + frameId + ''"'';
        if (window.ActiveXObject) {
            if (typeof uri == ''boolean'') {
                iframeHtml += '' src="'' + ''javascript:false'' + ''"'';

            }
            else if (typeof uri == ''string'') {
                iframeHtml += '' src="'' + uri + ''"'';

            }
        }
        iframeHtml += '' />'';
        jQuery(iframeHtml).appendTo(document.body);

        return jQuery(''#'' + frameId).get(0);
    },

    createUploadForm: function (id, fileElementId, data) {
        //create form	
        var formId = ''jUploadForm'' + id;
        var fileId = ''jUploadFile'' + id;
        var $form = jQuery(''<form  action="" method="POST" name="'' + formId + ''" id="'' + formId + ''" enctype="multipart/form-data"></form>'');
        if (data) {
            for (var i in data) {
                jQuery("<input type=''hidden'' name=''" + i + "'' value=''" + data[i] + "'' />").appendTo($form);
            }
        }
        //console.log(data);
        //console.log("基于官网的二次修改,作者:HandLoong");
        var oldElement = jQuery(''#'' + fileElementId);
        var newElement = jQuery(oldElement).clone();
        jQuery(oldElement).attr(''id'', fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo($form);

        //var form = jQuery.createUploadForm(id, s.fileElementId, s.data);


        //set attributes
        $form.css(''position'', ''absolute'');
        $form.css(''top'', ''-1200px'');
        $form.css(''left'', ''-1200px'');
        $form.appendTo(''body'');
        //console.log("创建一个from");
        return $form;
    },

    ajaxFileUpload: function (s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var $form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ''undefined'' ? false : s.data));
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = ''jUploadFrame'' + id;
        var formId = ''jUploadForm'' + id;
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {
            var io = document.getElementById(frameId);
            try {
                if (io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status);

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function () {
                    try {
                        jQuery(io).remove();
                        jQuery(form).remove();

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) {
            setTimeout(function () {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");
            }, s.timeout);
        }
        try {

            //var form = jQuery(''#'' + formId);
            $form.attr(''action'', s.url);
            $form.attr(''method'', ''POST'');
            $form.attr(''target'', frameId);
            if ($form.encoding) {
                $form.attr(''encoding'', ''multipart/form-data'');
            }
            else {
                $form.attr(''enctype'', ''multipart/form-data'');
            }
            console.log($form);
            $form.submit();

        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }

        jQuery(''#'' + frameId).load(uploadCallback);
        return { abort: function () { } };

    },

    uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();

        return data;
    },

    handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it  
        if (s.error) {
            s.error.call(s.context || s, xhr, status, e);
        }

        // Fire the global callback  
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
        }
    }
})

 

最后结果:

.Net MVC 用 ajaxfileupload 上传图片

.Net MVC 用 ajaxfileupload 上传图片

导入js

<script src="~/Scripts/ajaxfileupload.js"></script>

cshtml

<style>
   #oDiv {
      height: 200px;
      width: 200px;
      border: 1px solid #000;
      text-align: center;
      margin-bottom: 10px;
    }
</style>

<div>
    <div id="oDiv">
        <img src="" id="showPic"/>
    </div>
    <input type="file"  id="oInput" name="file" onchange="upload_cover(this)"/>
    <input type="text" id="ImageUrl" name="ImageUrl" placeholder="defaultPath" value="" />
</div>  

主要是type="file"的input ,特别注意,它的name="file", 后台接收写的样式一定也要是file

js

function upload_cover(obj) {
    //回传后缀
    var filePath = $("input[name=''file'']").val();
    var extStart = filePath.lastIndexOf(".");
    var ext = filePath.substring(extStart, filePath.length).toUpperCase();

    ajax_upload(obj.id, function (data) { //function(data)是上传图片的成功后的回调方法
        var isrc = data.relatPath.replace(/\/\//g, ''/''); //获取的图片的绝对路径
        $(''#image'').attr(''src'', basePath + isrc).data(''img-src'', isrc); //给<input>的src赋值去显示图片
    }, ext);
}

//具体的上传图片方法
function ajax_upload(feid, callback, ext) {
    if (image_check(feid)) {
        $.ajaxFileUpload({
            url: "/Company/UploadImage",
            secureuri: false,
            fileElementId: feid,
            dataType: ''json'',
            data: {fileType: ext},//增加推送的属性
            type: ''post'',
            async: true,
            secureuri: false,
            success:
            function (data) {
                alert(data.imagePath);
                $("#ImageUrl").val(data.imagePath);
                $("#showPic").attr("src", data.imagePath);
            },
            error:
            function (data) {
                alert(data);
            }
        });
    }
    };
    function image_check(feid) { //自己添加的文件后缀名的验证
        var img = document.getElementById(feid);
        return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
            modals.info(''图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。'');
            return false;
        })();
    }
        

controller

[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file)
{
    //获取图片后缀
    string fileType = Request.Form["fileType"];
    // 时间
    string now =  DateTime.Now.ToString("yyyyMMddHHmmssffff");
    //文件存放的文件路径
    string folder = HttpContext.Server.MapPath("/Content/images/companies/");

    // 保存文件
    string filePath = Path.Combine(folder, now + fileType);
    file.SaveAs(filePath);
    //切出相对路径
    string subFilePath = filePath.Substring(filePath.LastIndexOf("\\Content"));
    JsonResult json = new JsonResult();
    json.ContentType = "text/html";
    json.Data = new { imagePath = subFilePath, success = true };

    return json;
    //return Content(filePath);
}

注意: UploadImage(HttpPostedFileBase file){} 里面的file 一定要是前台 name="file"

返回的json不可以直接回传,需要新建一个JsonResult , 备注json.ContentType = "text/html"; 否则默认是application/json,前台html无法识别

 

关于asp.net – 如何将ContextKeys属性用于AjaxFileUpload控件?contextclick的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于$.ajaxFileUpload、$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、.net mvc ajaxfileupload.js 上传文件、.Net MVC 用 ajaxfileupload 上传图片等相关知识的信息别忘了在本站进行查找喔。

本文标签: