如何使用 AjaxFileUpload 控件的 ContextKeys 属性?

Pac*_*dez 5 asp.net ajaxcontroltoolkit

我开始研究 AjaxFileUpload 控件,特别是 ContextKeys 属性。但是,我不明白如何使用它。

文档中提到 AjaxFileUpload 时,ContextKeys 用于在上传文件时将信息传递到服务器。但没有提供示例。网上有什么例子可以看吗?

Yur*_*kiy 4

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

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

我将显示更改以及必须更改的文件名。

服务器/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs文件

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

/// <summary>
/// Gets or sets the context keys.
/// </summary>
public string ContextKeys
{
    get;
    set;
}
Run Code Online (Sandbox Code Playgroud)

之后打开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"];
Run Code Online (Sandbox Code Playgroud)

这就是我们需要对服务器代码进行的所有更改。现在我们需要修改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);
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面看到的,我们将 contextKey 添加到表单数据中,并通过 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
Run Code Online (Sandbox Code Playgroud)

另外,如果您将按照此处链接OnClientUploadStarted的建议实现客户端事件,您可以将您的 contextKeys 从客户端传递到服务器:

 function uploadStarted(sender, args) {
      sender.contextKeys = { "first": "1", "second": "2" };
 }
Run Code Online (Sandbox Code Playgroud)