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 UploaderPLUpload. 所有这些插件都会检测客户端浏览器是否支持 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 回答