亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 jQuery 和 C# ASP.NET MVC 通過 FormData 上傳文件

使用 jQuery 和 C# ASP.NET MVC 通過 FormData 上傳文件

C#
holdtom 2023-08-13 13:55:05
我有點不知道該怎么辦。我試圖一鍵上傳文件及其表單數據,但無法獲取該文件。我嘗試檢查客戶端中的文件,沒有問題,但是當控制器中接收文件時,它是空的。問題如何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);
查看完整描述

1 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

為什么是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);

}

所以,這就是你可以做到這一點的方法。


查看完整回答
反對 回復 2023-08-13
  • 1 回答
  • 0 關注
  • 212 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號