代码之家  ›  专栏  ›  技术社区  ›  CoffeeCode

ASP.NET MVC中的jquery ajax上载文件

  •  56
  • CoffeeCode  · 技术社区  · 16 年前

    我有一个文件在我的视图中

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

    以及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) {}
    });
    

    但是里面没有文件 请求.files . Ajax请求有什么问题?

    5 回复  |  直到 8 年前
        1
  •  111
  •   Ajeesh M    11 年前

    Upload files using AJAX in ASP.Net MVC

    自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;
    }   
    

    控制器

    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");
    }
    

    编辑 :HTML

    <form id="uploader">
        <input id="fileInput" type="file" multiple>
        <input type="submit" value="Upload file" />
    </form>
    
        2
  •  20
  •   M.Babcock    10 年前

    Ajax文件上载现在可以通过传递 FormData 反对 data 的属性 $.ajax 请求。

    正如OP特别要求jquery实现一样,这里是:

    <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 });
    }
    

    有关的详细信息 FormData at MDN

        3
  •  5
  •   Nick Craver    16 年前

    您不能通过Ajax上传文件,您需要使用iframe或其他一些技巧来进行完整的回发。这主要是出于安全考虑。

    Here's a decent write-up including a sample project 使用Steve Sanderson的swfupload和asp.net MVC。这是我读到的第一件事,让它与ASP.NET MVC一起正常工作(当时我也是MVC的新手),希望它对您有帮助。

        4
  •  0
  •   sandeep    12 年前

    如果使用Ajax发布表单,则不能 使用$.Ajax方法发送图像, 您必须使用经典的xmlhttpobject方法保存图像, 它的其他替代方法是使用提交类型而不是按钮

        5
  •  -1
  •   ddagsan    8 年前

    在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>