2013-08-10 4 views
1

Я пытаюсь получить текстовое поле FileDescription asp: text для сохранения в db, когда пользователь нажимает кнопку «Загрузить», но возвращается обратно. Что я делаю не так?ajaxToolkit: описание файла захвата AjaxFileUpload

это в моем файле upload.aspx

 <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" 
     ThrobberID="myThrobber" OnUploadComplete="AjaxFileUpload1_UploadComplete" 
     ContextKeys="" 
     AllowedFileTypes="jpg,jpeg,doc,xls" 
     MaximumNumberOfFiles="1" 
     runat="server"/> 
     </div> 

     File Description<asp:TextBox ID="FileDescription" Width="200" runat="server" ></asp:TextBox> 

and this is in my upload.cs file 
    protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e) 
     { 
      string sFileDescription = FileDescription.Text; 
      string filePath = "~/" + e.FileName; 
      AjaxFileUpload1.SaveAs(filePath); 

     } 
+0

Так что, когда вы вводите текст и установить точку останова на sFileDescription не показывать текст в этом объекте? – vikingben

+0

правильный. у этого парня была такая же проблема. и похоже, что это по дизайну. пытаясь разобраться в работе. http://stackoverflow.com/questions/16265922/ajax-control-toolkit-fileupload – user713813

+0

попробуйте поместить кнопку asp рядом с AjaxFileUpload. Он должен работать при нажатии кнопки –

ответ

2

Давайте добавим отдельные описания для каждого загружаемого файла. Для этого вам необходимо скачать источники AjaxControlToolkit из Codeplex (вот ссылка на скачивание: Latest toolkit sources и изменить три файла:

  1. AjaxFileUpload.Item.pre.js
  2. AjaxFileUpload.Control.pre.js
  3. AjaxFileUpload.css

Новое содержание AjaxFileUpload.Item.pre.js файл:

/// <reference path="../../../client/microsoftajax.extended/common/common.pre.js" /> 

Type.registerNamespace("Sys.Extended.UI.AjaxFileUpload"); 
Type.registerNamespace("AjaxFileUpload"); 

Sys.Extended.UI.AjaxFileUpload.Item = function (parentId, fileItem, onRemoveItem) { 
    this._deleteButton = null; 
    this._parentId = parentId; 
    this._inputElementValue = fileItem.value; 
    this._id = fileItem.id; 
    this._slices = fileItem.slices; 
    this._sliceIndex = 0; 

    this._fileInfoContainer = null; 
    this._fileStatusText = null; 
    this._isUploaded = false; 
    this._isUploading = false; 
    this._fileSize = 0; 
    this._fileName = ""; 
    this._fileType = ""; 
    this._bytesUploaded = 0; 

    this._fileComment = null; 

    this._ui = this.initUI(onRemoveItem); 
}; 

Sys.Extended.UI.AjaxFileUpload.Item.prototype = { 
    initUI: function (onRemoveItem) { 

     var self = this, file = this._inputElementValue, utils = new Sys.Extended.UI.AjaxFileUpload.Utils(), 
      isHtml5Support = utils.checkHtml5BrowserSupport(), 

      // generate unique id for each item 
      id = this._id, 

      // create line item container 
      container = $common.createElementFromTemplate({ 
       nodeName: "div", 
       properties: { 
        id: this._parentId + '_FileItemContainer_' + id, 
       }, 
       cssClasses: ['ajax__fileupload_fileItemInfo'] 
      }), 

      // create file info/status container 
      fileInfoContainer = $common.createElementFromTemplate({ 
       nodeName: "div", 
       properties: { 
        id: this._parentId + '_FileInfoContainer_' + id, 
        style: { 
         display: 'inline-block' 
        } 
       } 
      }), 

      // create file info placeholder 
      fileInfoText = $common.createElementFromTemplate({ 
       nodeName: "span", 
       properties: { 
        id: this._parentId + '_FileItemInfo_' + id 
       }, 
       cssClasses: ['ajax__fileupload_fileItemInfo'] 
      }), 

      // create file status placeholder 
      fileStatusText = $common.createElementFromTemplate({ 
       nodeName: "span", 
       properties: { 
        id: this._parentId + '_FileItemStatus_' + id 
       }, 
       cssClasses: ['uploadstatus'] 
      }), 

      commentContainer = $common.createElementFromTemplate({ 
       nodeName: 'div', 
       cssClasses: ['ajax__fileupload_fileItem_commentContainer'] 
      }), 

      fileComment = $common.createElementFromTemplate({ 
       nodeName: "input", 
       properties: { 
        id: this._parentId + '_FileItemComment_' + id, 
        type: 'text', 
        style: { 
         width: '100%' 
        } 
       }, 
       cssClasses: ['ajax__fileupload_fileItem_commentInput'] 
      }), 

      // init remove button 
      deleteButton = $common.createElementFromTemplate({ 
       nodeName: "div", 
       properties: { 
        id: this._parentId + '_FileItemDeleteButton_' + id 
       }, 
       cssClasses: ['removeButton'] 
      }); 

     this._fileName = utils.getFileName(file); 

     if (isHtml5Support) { 
      this._fileSize = file.size; 
      var fType = file.type ? '<span class="filetype">(' + file.type + ')</span>' : ''; 
      fileInfoText.innerHTML = '<span class="filename">' + this._fileName + '</span> ' 
       + fType 
       + ' - <span class="filesize">' + utils.sizeToString(file.size) + '</span> '; 
      this._fileType = file.type; 
     } else { 

      fileInfoText.innerHTML = '<span class="filename">' + this._fileName + '</span>'; 
      this._fileType = utils.getFileType(file); 
     } 

     commentContainer.innerHTML = '<label class="ajax__fileupload_fileItem_commentLabel" for="' + this._parentId + '_FileItemComment_' + id + '">Description:</label>'; 
     commentContainer.appendChild(fileComment); 

     fileInfoContainer.appendChild(fileInfoText); 
     fileInfoContainer.appendChild(fileStatusText); 
     fileInfoContainer.appendChild(commentContainer); 

     $common.setText(deleteButton, Sys.Extended.UI.Resources.AjaxFileUpload_Remove); 
     $addHandlers(deleteButton, { 
      'click': Function.createDelegate(this, function() { 
       onRemoveItem(self); 
      }) 
     }); 

     // build the line item 
     if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version <= 8) { 
      container.appendChild(deleteButton); 
      container.appendChild(fileInfoContainer); 
     } 
     else { 
      container.appendChild(fileInfoContainer); 
      container.appendChild(deleteButton); 
     } 


     this._fileInfoContainer = fileInfoContainer; 
     this._deleteButton = deleteButton; 
     this._fileStatusText = fileStatusText; 
     this._fileComment = fileComment; 

     return container; 
    }, 

    setStatus: function (fileStatusText, text) { 
     $common.setText(this._fileStatusText, ' (' + text + ')'); 
     this._fileInfoContainer.setAttribute('class', fileStatusText + 'State'); 
    }, 

    disabled: function (on) { 
     if (on) 
      this._deleteButton.disabled = this._fileComment.disabled = 'disabled'; 
     else 
      this._deleteButton.disabled = this._fileComment.disabled = ''; 
    }, 

    hide: function() { 
     this._deleteButton.style.visibility = 'hidden'; 
     this._fileComment.readOnly = true; 
    }, 

    destroy: function() { 
     $common.removeElement(this._inputElementValue); 
     $common.removeElement(this._deleteButton); 
     $common.removeElement(this._fileComment); 
     $common.removeElement(this._ui); 
    }, 

    get_inputElementValue: function() { 
     return this._inputElementValue; 
    }, 

    appendNodeTo: function (parent) { 
     parent.appendChild(this._ui); 
    }, 

    removeNodeFrom: function (parent) { 
     parent.removeChild(this._ui); 
    }, 

    get_fileComment: function() { 
     return this._fileComment.value; 
    } 
}; 

В этом коде добавлены новые поля классов _fileComment, новая функция get_fileComment и модифицированный initUI, инвалидов, скрыть и уничтожить функции. После этих изменений каждый элемент файла будет иметь отдельное текстовое поле для описания файла.

После этого немного измените AjaxFileUpload.Control.pre.js файл. Перепишите doneAndUploadNextFile функции, как показано ниже:

doneAndUploadNextFile: function (fileItem) { 
    /// <summary> 
    /// Mark fileItem as uploaded, and upload next file in queue. 
    /// </summary> 
    /// <param name="fileItem">Uploaded File</param> 

    // send message to server to finalize this upload 
    var xhr = new XMLHttpRequest(), 
     self = this; 

    xhr.open("POST", "?contextKey="+ this._contextKey +"&done=1&guid=" + fileItem._id + "&comment=" + fileItem.get_fileComment(), true); 
    xhr.onreadystatechange = function (e) { 
     if (xhr.readyState == 4) { 
      if (xhr.status == 200) { 

       // Mark as done and invoke event handler 
       self.raiseUploadComplete(Sys.Serialization.JavaScriptSerializer.deserialize(xhr.responseText)); 

       // Upload next file 
       self._processor.startUpload(); 

      } else { 
       // finalizing is error. next file will not be uploaded. 
       self.setFileStatus(fileItem, 'error', Sys.Extended.UI.Resources.AjaxFileUpload_error); 
       self.raiseUploadError(xhr); 
       throw "error raising upload complete event and start new upload"; 
      } 
     } 
    }; 
    xhr.send(null); 
} 

И последний шаг является AjaxFileUpload.css файл. Изменение Heigh CSS рассердить в .ajax__fileupload_fileItemInfo определения класса и добавить три дополнительных классов для описания:

.ajax__fileupload_fileItemInfo { 
    line-height: 20px; 
    height: 44px; 
    margin-bottom: 2px; 
    overflow: hidden; 
} 

.ajax__fileupload_fileItem_commentContainer { 
    display: table; 
    width: 100%; 
} 

.ajax__fileupload_fileItem_commentLabel { 
    display: table-cell; 
    width: 1px; 
    white-space: nowrap; 
    padding-right: 5px; 
} 

.ajax__fileupload_fileItem_commentInput { 
    display: table-cell; 
    width: 100%; 
} 

После этих изменений перестраивать инструментарий решения и использовать пользовательские библиотеки DLL. Теперь вы можете получить опубликовали описание из строки запроса в обработчик OnUploadComplete событий: var comment = Request.QueryString["comment"];

Смежные вопросы