簡體   English   中英

MVC - 單擊時打開文件上傳對話框 (vb.net)

[英]MVC - Open File Upload Dialog On Click (vb.net)

我希望當用戶單擊<a> ,在服務器端打開文件對話框,然后在完成后向用戶返回“ok”消息。 我想到了這一點,在觀點上:

<a onclick="uploadFile()">Edit</a>

Javascript:

function uploadFile() {

            //Call the controller, open file dialog at server side, and 
            //return message to the user.
            //alert(responseMessage)

        }

方法:

Function OpenFileDialog() As ActionResult

            //open file dialog, upload the file
            //Dim message = success or not

            Return Content(message)
        End Function

我如何在服務器端的 vb.net 中打開文件上傳對話框?

沒有辦法隨心所欲地彈出文件對話框。 這只會在單擊文件輸入時發生。 也就是說,您可以在鏈接上捕獲單擊事件,然后使用 JavaScript 單擊文件輸入。 然后,您只需要處理文件輸入(即用戶選擇一個或多個文件)上的更改事件以觸發包含文件的 AJAX 請求。 但是,通過 AJAX 上傳文件需要文件 API,它是 HTML5 的一部分。 這意味着這只適用於現代瀏覽器(IE10+)。 要在以前版本的 IE 中上傳文件而不使用刷新頁面的傳統表單發布,您必須使用為異步上傳文件而創建的 Flash 或 Java 控件。 不過,這超出了本答案的范圍。

 document.getElementById('FileUploadLink').addEventListener('click', function (e) { e.preventDefault(); document.getElementById('FileUploadInput').click(); }); document.getElementById('FileUploadInput').addEventListener('change', function () { var fileInput = this; var formData = new FormData(); for (var i = 0; i < fileInput.files.length; i++) { var file = fileInput.files[i]; formData.append('upload', file, file.name); } var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload/handler', true); xhr.onload = function () { if (xhr.status === 200) { // file(s) uploaded successfully } else { // error uploading file(s) } }; // Commented to not send a real AJAX request for this example // Uncomment in your real code to actually send the request // xhr.send(formData); });
 <a id="FileUploadLink" href="#">Upload File</a> <input type="file" id="FileUploadInput" style="display:none">

然后,在服務器端,您的 MVC 操作將如下所示:

public ActionResult UploadFile(HttpPostedFileBase upload)

請注意,動作參數的名稱與傳遞給formData.append的字符串formData.append 這很重要。

要進行多文件上傳,您只需要更改一些內容:

  1. multiple添加到文件輸入:

     <input type="file" id="FileUploadInput" style="display:none" multiple>
  2. 更改formData.append行以使名稱成為數組:

     formData.append('uploads[]', file, file.name);
  3. 更改操作方法簽名以接受List<HttpPostedFileBase>

     public ActionResult UploadFiles(List<HttpPostedFileBase> uploads)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM