2010-03-11 149 views
48

Tôi có một tập tin trong quan điểm của tôijQuery ajax upload file trong asp.net MVC

<form id="upload" enctype="multipart/form-data"> 
    <input type="file" name="fileUpload" id="fileUpload" size="23" /> 
</form> 

và một yêu cầu ajax

$.ajax({ 
    url: '<%=Url.Action("JsonSave","Survey") %>', 
    dataType: 'json', 
    processData: false, 
    contentType: "multipart/mixed", 
    data: { 
     Id: selectedRow.Id, 
     Value: 'some date was added by the user here :))' 
    }, 
    cache: false, 
    success: function (data) {} 
}); 

nhưng không có tập tin trong Request.Files. Có gì sai với yêu cầu ajax?

+0

js trên không thể tải lên các tệp như thế này. Tốt hơn để sử dụng hành vi tải lên mặc định của trình duyệt. – Hogan

Trả lời

95

Upload files using AJAX in ASP.Net MVC

Mọi thứ đã thay đổi kể từ HTML5

Javascript

document.getElementById('uploader').onsubmit = function() { 
    var formdata = new FormData(); //FormData object 
    var fileInput = document.getElementById('fileInput'); 
    //Iterating through each files selected in fileInput 
    for (i = 0; i < fileInput.files.length; i++) { 
     //Appending each file to FormData object 
     formdata.append(fileInput.files[i].name, fileInput.files[i]); 
    } 
    //Creating an XMLHttpRequest and sending 
    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', '/Home/Upload'); 
    xhr.send(formdata); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4 && xhr.status == 200) { 
      alert(xhr.responseText); 
     } 
    } 
    return false; 
} 

khiển

public JsonResult Upload() 
{ 
    for (int i = 0; i < Request.Files.Count; i++) 
    { 
     HttpPostedFileBase file = Request.Files[i]; //Uploaded file 
     //Use the following properties to get file's name, size and MIMEType 
     int fileSize = file.ContentLength; 
     string fileName = file.FileName; 
     string mimeType = file.ContentType; 
     System.IO.Stream fileContent = file.InputStream; 
     //To save file, use SaveAs method 
     file.SaveAs(Server.MapPath("~/")+ fileName); //File will be saved in application root 
    } 
    return Json("Uploaded " + Request.Files.Count + " files"); 
} 

EDIT: HTML

<form id="uploader"> 
    <input id="fileInput" type="file" multiple> 
    <input type="submit" value="Upload file" /> 
</form> 
+4

Truyền thuyết! Cuối cùng là một giải pháp làm việc với MVC! – kravits88

+1

Bạn có thể thêm mã cho chế độ xem không? HTML .. cho câu trả lời này. –

+0

sau khi chi tiêu 7 giờ cuối cùng một cái gì đó mà thực sự hoạt động !!! – Mayank

5

Bạn không thể tải tệp lên qua ajax, bạn cần sử dụng iFrame hoặc một số mẹo nhỏ khác để thực hiện đăng lại toàn bộ. Điều này chủ yếu là do vấn đề an ninh.

Here's a decent write-up including a sample project sử dụng SWFUpload và ASP.Net MVC của Steve Sanderson. Đó là điều đầu tiên tôi đọc nhận được điều này làm việc đúng với Asp.Net MVC (tôi đã mới đến MVC tại thời điểm đó), hy vọng nó là hữu ích cho bạn.

+8

Điều đó không đúng; bạn có thể gửi dữ liệu biểu mẫu qua ajax. –

+0

@JoshM. Có, nhưng bạn không thể gửi tệp qua AJAX mà không có một số giải pháp bên ngoài. – Kehlan

+6

@kehrk: Với các đối tượng FormData và File mới trong HTML5, bạn thực sự có thể tải lên các tệp thông qua AJAX. Hãy thử cách này: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications. – jrista

0

Nếu bạn đăng hình thức sử dụng ajax thì bạn có thể không gửi hình ảnh sử dụng $ .ajax phương pháp, bạn phải sử dụng phương pháp xmlHttpobject cổ điển để lưu hình ảnh, thay thế khác sử dụng loại gửi thay vì nút

11

Tải lên tệp AJAX bây giờ có thể bằng cách chuyển đối tượng FormData đến thuộc tính data của yêu cầu $.ajax.

Như OP đặc biệt yêu cầu một việc thực hiện jQuery, here you go:

<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST"> 
    <input type="file" name="fileUpload" id="fileUpload" size="23" /><br /> 
    <button>Upload!</button> 
</form> 
$('#upload').submit(function(e) { 
    e.preventDefault(); // stop the standard form submission 

    $.ajax({ 
     url: this.action, 
     type: this.method, 
     data: new FormData(this), 
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (data) { 
      console.log(data.UploadedFileCount + ' file(s) uploaded successfully'); 
     }, 
     error: function(xhr, error, status) { 
      console.log(error, status); 
     } 
    }); 
}); 
public JsonResult Survey() 
{ 
    for (int i = 0; i < Request.Files.Count; i++) 
    { 
     var file = Request.Files[i]; 
     // save file as required here... 
    } 
    return Json(new { UploadedFileCount = Request.Files.Count }); 
} 

Thông tin thêm về FormData at MDN

+2

Đẹp. Cảm ơn bạn! Câu trả lời hay nhất tôi đã tìm thấy trên câu hỏi SEVERAL. – Jess

0

Tôi có một mẫu như thế này trên phiên bản vuejs: v2 .5.2

<form action="url" method="post" enctype="multipart/form-data"> 
    <div class="col-md-6"> 
     <input type="file" class="image_0" name="FilesFront" ref="FilesFront" /> 
    </div> 
    <div class="col-md-6"> 
     <input type="file" class="image_1" name="FilesBack" ref="FilesBack" /> 
    </div> 
</form> 
<script> 
Vue.component('v-bl-document', { 
    template: '#document-item-template', 
    props: ['doc'], 
    data: function() { 
     return { 
      document: this.doc 
     }; 
    }, 
    methods: { 
     submit: function() { 
      event.preventDefault(); 

      var data = new FormData(); 
      var _doc = this.document; 
      Object.keys(_doc).forEach(function (key) { 
       data.append(key, _doc[key]); 
      }); 
      var _refs = this.$refs; 
      Object.keys(_refs).forEach(function (key) { 
       data.append(key, _refs[key].files[0]); 
      }); 

      debugger; 
      $.ajax({ 
       type: "POST", 
       data: data, 
       url: url, 
       cache: false, 
       contentType: false, 
       processData: false, 
       success: function (result) { 
        //do something 
       }, 

      }); 
     } 
    } 
}); 
</script> 
Các vấn đề liên quan