0

私の MVC アプリケーションでは、ユーザーがファイルをアップロードできるようにしています。ユーザーがファイルのアップロード リンクをクリックするたびに、これがリンクになります。

  <a class="upload" onclick="upload(this);">

ファイルのアップロードは、モーダル ボックスで開く必要があります。

function upload(box) {
       var box = dhtmlx.modalbox({
           title: "Upload File",
           text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' style='width: 86px' onclick='save_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
           width: "300px"
       });
   }
   function close_file(box) {

       dhtmlx.modalbox.hide(box);

   }

   function save_file(box) {
       var file = $("#file").val();
       if (file == "") {
           alert("Enter the URL");
           return false;

       dhtmlx.modalbox.hide(box);
       dhtmlx.message("Uploading the file");
       $.post("/FileUpload/Upload",
       { file: '' + file + '' });
   }
  and the controller code is 
[HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        SaveFile(file);
        return RedirectToAction("Index");
    }

しかし、問題はエラーが発生していることです。つまり、file = null

4

1 に答える 1

1

AJAX リクエスト ( ) を使用してファイルをアップロードすることはできません$.post。お使いのブラウザが HTML5 File API をサポートしている場合は、新しいXHR2 object. Uploadifyそうでない場合は、Fine Uploaderやなどのファイル アップロード プラグインを使用できますPLUpload。これらのプラグインはすべて、クライアント ブラウザーが HTML5 File API をサポートしているかどうかを検出し、サポートしている場合はそれを使用し、サポートしていない場合は、非表示の iframe や Flash ムービーを使用するなどの標準的な手法にフォールバックします。それらのいずれかを使用する利点は、考えられるすべてのケースをコーディングする必要がないことです。

HTML5 File API を使用してファイルをアップロードする方法の例を次に示します。

function save_file(box) {
    var file = document.getElementById('file');
    if (file.value == '') {
        alert('Enter the URL');
        return false;
    }

    dhtmlx.modalbox.hide(box);
    dhtmlx.message('Uploading the file');

    var fd = new FormData();
    fd.append('file', file.files[0]);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/FileUpload/Upload', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert('file successfully uploaded to the server');
        }
    };
    xhr.send(fd);
}
于 2013-03-18T07:13:47.317 に答える