【问题标题】:Upload file with FormData using jQuery and C# ASP.NET MVC使用 jQuery 和 C# ASP.NET MVC 上传带有 FormData 的文件
【发布时间】:2023-04-03 23:12:01
【问题描述】:

我有点不知道该怎么做。我正在尝试一键上传文件及其表单数据,但我无法获取该文件。我尝试在客户端查看文件,没有问题,但是在Controller中接收文件时,它是空的。

问题

如何使用 jQuery 沿其formData 上传文件?

查看

假设其他字段

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

                con.Open

                data = Convert.ToString(com.ExecuteScalar()); 

                var file_path = Path.Combine(path, data + Extension);
                fileUpload.SaveAs(file_path);
            }            
        } 
        catch (Exception ex)
        {
            data = ex.Message;
        }

        // data returns id if success or error message
    }

    return data;
}

【问题讨论】:

  • 离题:SqlCommand 实现了IDisposable 并且应该像SqlConnection 一样包裹在using 语句中。

标签: c# jquery asp.net-mvc file-upload


【解决方案1】:

为什么是serialize 表单?此方法创建一个可以发送到服务器的字符串,但这不是您想要做的......如果是文件上传;在此处查看.serialize() 功能说明。

FormData 类型会自动管理表单的 enctype(请参阅此处的 MDN),因此您可以省略它——尽管您应该考虑使用它,因为它有助于团队中的其他成员理解意图。如果你想使用普通的 jQuery,你可以简单地将 formData 变量附加到 $.ajax 调用的 data 字段。看这里,

/*
* 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 上传了文件。

您可以查看我在这里发布的完整文章,Uploading the files — HTML5 and jQuery Way!

哦,别忘了评论中提出的建议,

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

所以,这就是你可以做到这一点的方法。

【讨论】:

  • 谢谢!我终于明白了它确实出错的地方。该功能现在正在运行。
猜你喜欢
  • 2015-11-16
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2015-06-19
  • 2010-12-31
相关资源
最近更新 更多