【问题标题】:How to save file using ajax如何使用ajax保存文件
【发布时间】:2019-07-04 03:26:21
【问题描述】:

我正在尝试通过 ajax 向控制器发送 FormData 来保存文件,问题是即使我使用 FormData 函数将所有变量转换为一种形式,我的 ajax 也无法正常工作。

我尝试使用表单,但在表格中,我无法使用表单标签,因为我的按钮在另一个 td 中。当我将它用于整个表时,它也不起作用,我创建了FormData,我在其中附加了所有变量,其余变量都在工作,但图像没有。

index.cshtml:

<tr class="form" style="display:none">

    <td class="name">
        <input type="text" name="Jméno" value="" />
    </td>
    <td class="price">
        <input type="number" name="Cena" value="" />
    </td>
    <td class="quantity">
        <input type="number" name="Mnozstvi" value="" />
    </td>
    <td class="image">
        <input type="file" id="fileOne" name="fileOne" runat="server" />
    </td>
    <td>
        <button class="FirstSave" type="button" id="btnUpload">Uložit</button>

        <button class="getBack">Zahodit</button>

    </td>
</tr>

这是我的 JavaScript

$(".FirstSave").click(function () {

      let file = document.getElementById('fileOne').file;
      let form = new FormData;

      form.append('Image', file);
      form.append('Name', name);
      form.append('Price', price);
      form.append('Quantity', quantity);
      $.ajax({
         url: "Insert",
         method: "POST",
         cache: false,
         processData: false,
         data: form,
    });
})

产品获取器和设置器

public class Product
{
    public string Name { get; set; }
    public int Price { get; set; }
    public int Quantity { get; set; }
    public string ImageUrl { get; set; }
    public HttpPostedFileBase Image { get; set; }

}

产品控制器

[HttpPost]
public ActionResult Insert(Product product)
{
    HttpPostedFileBase file = product.Image;
    if (file != null)
    {
        var fileName = Path.GetFileName(file.FileName);
        product.ImageUrl = Path.Combine(Server.MapPath("~/Content/Images/Products/"), fileName);
        file.SaveAs(product.ImageUrl);
    }
    return null;
}

【问题讨论】:

    标签: jquery asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    这是对我有用的代码:

    $(document).on("submit", "#myFormId", function (event) {
          event.preventDefault();
          event.stopImmediatePropagation();
    
          var formData = new FormData(this);
    
          $.ajax({
               url: 'my url',
               type: 'POST',
               data: formData,
               success: function (response) {
                   if (response) {
                       // Do whatever you want to do with response 
                   }
               },
               error: function (error) {
                   console.log(error)
               },
               cache: false,
               contentType: false,
               processData: false
          });
          return false;
     });
    

    我发现您在 ajax 设置中缺少 contentType: false。这是使用 ajax 上传文件所必需的。

    【讨论】:

    • 感谢您的回答,我已经在代码中添加了 contentType:false 但图像仍然没有保存到文件中。
    • @Michael 确认您的表单标签包含enctype="multipart/form-data" 属性。
    【解决方案2】:

    改用这个:

    var fileName = file.FileName;
    

    更换你的线路

    var fileName = Path.GetFileName(file.FileName);
    

    如果我要更改您的代码:

        var fileName = file.FileName;
        product.ImageUrl = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
        file.SaveAs(product.ImageUrl);
    

    如果这还不够,请检查我用于上传的 js 代码:

    for (var x = 0; x < files.length; x++) {
        data.append("file" + x, files[x]);
    }
    

    【讨论】:

      【解决方案3】:
      • 首先确认你的表单标签包含表单 enctype="多部分/表单数据"。 第二次在你的 ajax 调用中添加 contentType: false

        $.ajax({ 网址:form_url, 类型:form_method, 内容类型:假, 数据:formData,});

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        • 2021-03-14
        • 2015-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多