簡體   English   中英

通過ajax post發送文件和表單數據

[英]Sending file together with form data via ajax post

我正在嘗試通過 ajax 上傳文件以及表單中的一些字段。 但是,它不起作用。 我得到這個錯誤。

未定義索引:- 文件

這是我的代碼。

HTML

<!-- File Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="file">Upload Software / File</label>
  
  <div class="col-md-4">
    <input id="file" name="file" class="input-file" type="file">
  </div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="price">Price($)</label>
  
  <div class="col-md-4">
    <input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
  </div>
</div>

阿賈克斯

$("#add_product").click(function(e) {
  e.preventDefault();
  product_name = $("product_name").val();
  //d = $("#add_new_product").serialize();
  
  $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: $("#add_new_product").serialize(),
    success: function(response) {
      //
      alert(response);

    }
  })
});

PHP

if (0 < $_FILES['file']['error']) {
  echo ":!";
} else {
  echo "ASa";
}

我在這里想念什么?

您可以嘗試使用FormData()嗎:

$("form#files").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

以上是一個示例代碼,但您可以使用它來修改它。

你可以使用 FormData

 $("#add_product").click(function(e) { e.preventDefault(); var fdata = new FormData() fdata.append("product_name", $("product_name").val()); if ($("#file")[0].files.length > 0) fdata.append("file", $("#file")[0].files[0]) //d = $("#add_new_product").serialize(); $.ajax({ type: 'POST', url: 'ajax.php', data: fdata, contentType: false, processData: false, success: function(response) { // alert(response); } }) });
 <!-- File Button --> <div class="form-group"> <label class="col-md-4 control-label" for="file">Upload Software / File</label> <div class="col-md-4"> <input id="file" name="file" class="input-file" type="file"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label" for="price">Price($)</label> <div class="col-md-4"> <input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required=""> </div> </div>

我們首先需要承認的是,我們需要將表單輸入數據和表單文件都附加到單個 FormData變量中。

這是我啟用多文件選項的解決方案,以便該解決方案適用於所有示例。

在大多數情況下,在輸入控件中包含name屬性以使其在服務器端正常工作是很重要的。 如果您使用的是 C#,那么您可以簡單地使用Request.Form["nameAttribute"]來簡單地獲取函數。 Java 和其他語言也是如此。

我的示例代碼是

 $(document).ready(function () //Setting up on Document to Ready Function { $("#btnUpload").click(function (event) { //getting form into Jquery Wrapper Instance to enable JQuery Functions on form var form = $("#myForm1"); //Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later. var params = form.serializeArray(); //Getting Files Collection var files = $("#File1")[0].files; //Declaring new Form Data Instance var formData = new FormData(); //Looping through uploaded files collection in case there is a Multi File Upload. This also works for single ie simply remove MULTIPLE attribute from file control in HTML. for (var i = 0; i < files.length; i++) { formData.append(files[i].name, files[i]); } //Now Looping the parameters for all form input fields and assigning them as Name Value pairs. $(params).each(function (index, element) { formData.append(element.name, element.value); }); //disabling Submit Button so that user cannot press Submit Multiple times var btn = $(this); btn.val("Uploading..."); btn.prop("disabled", true); $.ajax({ url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc method: "post", data: formData, contentType: false, processData: false, success: function () { //Firing event if File Upload is completed! alert("Upload Completed"); btn.prop("disabled", false); btn.val("Submit"); $("#File1").val(""); }, error: function (error) { alert("Error"); } }); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form enctype="multipart/form-data" method="post" id="myForm1"> <p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p> <p><input id="File1" type="file" multiple="multiple" /></p> <input id="btnUpload" type="button" value="Submit" /> </form>

對於一個工作示例(帶有處理程序的 asp.net C#),您可以訪問https://github.com/vibs2006/HttpFileHandlerFormDataSample上的示例代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM