問題描述

沒有使用任何形式,我可以使用 jQuery 使用 POST 方法將檔案/檔案從<input type="file"> 傳送到’upload.php’ 。輸入標籤不在任何表單標籤內。它獨立地站立。所以我不想使用像’ajaxForm’ 或’ajaxSubmit’ 這樣的 jQuery 外掛。

最佳解決方案

您可以使用 FormData 透過 POST 請求提交資料。這是一個簡單的例子:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

只要知道您的請求設定 (如 url,方法和引數資料),您就不必使用表單來製作 ajax 請求。

次佳解決方案

基於 this tutorial,這是一個非常基本的方法:

$('your_trigger_element_selector').on('click', function(){
    var data = new FormData();
    data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
    // append other variables to data if you want: data.append('field_name_x', field_value_x);

    $.ajax({
        type: 'POST',
        processData: false, // important
        contentType: false, // important
        data: data,
        url: your_ajax_path,
        dataType : 'json',
        // in PHP you can call and process file in the same way as if it was submitted from a form:
        // $_FILES['input_file_name']
        success: function(jsonData){
            ...
        }
        ...
    });
});

不要忘記新增正確的錯誤處理

第三種解決方案

這裡的所有答案仍在使用 FormData API 。它就像沒有表單的表單檔案上傳。您還可以使用 xmlHttpRequest 直接將檔案上傳到 POST 請求的正文內,如下所示:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

Content-TypeContent-Disposition 標頭用於說明我們傳送的內容 (mime-type 和檔名) 。

我也發貼類似的答案也是 here

第四種方案

步驟 1:建立 HTML 頁面放置 HTML 程式碼。

步驟 2:在 HTML 內碼表面底部 (頁尾) 建立 Javascript:並將 Jquery 程式碼放在指令碼標籤中。

步驟 3:建立 PHP 檔案和 PHP 程式碼複製過去。在 $.ajax 中的 Jquery 程式碼之後,程式碼 url 應用您的 php 檔名稱中哪一個。

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes
    }
  });
});

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

print_r($_FILES);
print_r($_POST);

第五種方案

對不起,那個人,但 AngularJS 提供了一個簡單而優雅的解決方案。

這是我使用的程式碼:



ngApp.controller('ngController', ['$upload',
function($upload) {

  $scope.Upload = function($files, index) {
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        file: file,
        url: '/File/Upload',
        data: {
          id: 1 //some data you want to send along with the file,
          name: 'ABC' //some data you want to send along with the file,
        },

      }).progress(function(evt) {

      }).success(function(data, status, headers, config) {
          alert('Upload done');
        }
      })
    .error(function(message) {
      alert('Upload failed');
    });
  }
};
}]);
.Hidden {
  display: none
}
<script src="https://googleajax.admincdn.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://googleajax.admincdn.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div data-ng-controller="ngController">
  <input type="button" value="Browse" onclick="$(this).next().click();" />
  <input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>

在伺服器端,我有一個帶有動作的 MVC 控制器,儲存在 Request.Files 集合中發現的檔案,並返回一個 JsonResult 。

如果你使用 AngularJS 嘗試這個,如果你不… 對不起,伴侶:-)

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇