使用 jQuery 和 C# ASP.NET MVC 通过 FormData 上传文件

我有点不知道该怎么办。我试图一键上传文件及其表单数据,但无法获取该文件。我尝试检查客户端中的文件,没有问题,但是当控制器中接收文件时,它是空的。


问题

如何formData使用 jQuery 上传文件?


看法

假设其他字段


<form id="_RegisterProduct" enctype="multipart/form-data">

    <div>

        <label>Product Description</label>

        <textarea id="product_description" name="_product_description"></textarea>

        <input type="file" 

               id="product_file"

               name="product_file" 

               class="dropify" />

    </div>

    <button type="submit" id="snippet_new_save">Register Product</button>

</form>


<script>

    $(function() {

        rules: {

            text: { required: true, minlength: 5 },

            number: { required: true, minlength: 1 }

        },


        submitHandler: function (form) {

            var fileUpload = $("#product_file").val();

            var formData = $("#_RegisterForm").serialize();

            var url = "@Url.Action("RegisterProduct", "Product")";


            $.get(url, { fileUpload: fileUpload, formData }, function (e) {

                if (e >= 1) {

                    console.log("success");

                } else {

                    console.log("error");

                }

            });

        }

    })

</script>

控制器

public string RegisterProduct(HttpPostedFileBase fileUpload, AB_ProductModel formData)

{

    var data = "";

    using (var con = new SqlConnection(Conn.MyConn()))

    {

        var path = Server.MapPath("~/Content/uploads/products");

        var Extension = "";

        var fileName = "";


        try

        {

            if(fileUpload.ContentLength > 0)

            {

                Extension = Path.GetExtension(fileUpload.FileName);

                fileName = Path.GetFileName(fileUpload.FileName);


                var com = new SqlCommand("dbo.sp_some_stored_procedure_for_saving_data", 

                    con);


holdtom
浏览 177回答 1
1回答

慕虎7371278

为什么是serialize表格?此方法创建一个可以发送到服务器的字符串,但这不是您想要做的......FormDatatype 会自动管理enctype您的表单,因此您可以省略它 - 尽管您应该考虑使用它,因为它可以帮助团队中的其他成员理解意图。如果您想使用纯 jQuery,您只需将formData变量附加到data调用的字段即可$.ajax。看看这里,/** i know id-based selection should only have 1 element, * otherwise HTML is invalid for containing multiple elements * with the same id, but this is the exact code i used back then, so using it again.**/var formData = new FormData($('#form')[0]);  $.ajax({    type: 'POST',    processData: false,    contentType: false,    data: formData,    success: function (data) {       // The file was uploaded successfully...       $('.result').text('File was uploaded.');    },    error: function (data) {       // there was an error.       $('.result').text('Whoops! There was an error in the request.');    }});这当然要求您的 HTML DOM 包含这些元素——我使用了几年前为我的文章编写的代码。其次,对于该功能的其他部分,我曾经Request.Files捕获可能已随请求上传的文件。files = Request.Files.Count;if(files > 0) {   // Files are sent!   for (int i = 0; i < files; i++) {      var file = Request.Files[i];      // Got the image...      string fileName = Path.GetFileName(file.FileName);      // Save the file...      file.SaveAs(Server.MapPath("~/" + fileName));   }}这样,我使用 jQuery 和FormData.您可以查看我在此处发布的完整文章,上传文件 — HTML5 和 jQuery 方式!哦,不要忘记评论中提出的建议,using (var com = new SqlCommand("dbo.sp_some_stored_procedure_for_saving_data", con)) {    con.Open(); // missed call?    data = Convert.ToString(com.ExecuteScalar());     // although, using should close here!    var file_path = Path.Combine(path, data + Extension);    fileUpload.SaveAs(file_path);}所以,这就是你可以做到这一点的方法。
打开App,查看更多内容
随时随地看视频慕课网APP