javascript - 无法将内容附加到 FormData()

标签 javascript php jquery ajax form-data

我有两个不同的 JS 函数来处理图像上传。一个读取文件并(全局)创建 FormData 对象,另一个通过 AJAX 将其发送到 PHP 文件。

即使 file 有效,我也无法将其附加到 FormData。也没有字符串。事实证明,我只是通过 Ajax 发送空的 XHRequest,因为我没有从 PHP 获得任何其他内容,然后是空数组。

由于第一个 JS 函数全局初始化 formData 变量,所以第二个函数使用它应该没有问题,对吗?

我的 Javascript 看起来像这样(我注释掉了一些不必要的行:

   $(document).ready(function(){

      var formUplImg = $('.form-upl-img');
      var fileInput  = $('.file-input');

      // Analyse files from input immediately
      fileInput.on('change', function(){
         readFile($(this).attr('id'));
      })

      // Upload images on submit
      formUplImg.on('submit', function(event) {
         uploadImg($(this), event);
      });



      function readFile(id){
         // Grab file that's supposed to be uploaded
         var fileInput = document.getElementById(id);
         var fileCount = fileInput.files.length;
             formData  = new FormData();

         // If there is no file
         if( fileCount!= 1 ){
            // goodImg    = false;
            // Error message
            // showMsgBar(iClose, 'Da ist nichts.', 'Bitte wähle zuerst eine Datei aus.', red);

         // If there is a file
         } else {
            // Save file attributes
            var file      = fileInput.files[0];
            var fileName  = fileInput.files[0].name;
            var fileSize  = fileInput.files[0].size;
            var fileType  = fileInput.files[0].type;

            // If file is not an image
            if( !fileType.match(/image.*/) ) {
               // goodImg    = false;
               // Error message
               // showMsgBar(iClose, 'Ungültiger Dateityp.', 'Das Bild muss ein JPG, PNG, GIF oder SVG sein.', red);

            // If file is an image
            } else {
               // If file size exceeds 3MB
               if( fileSize > 3145728 ) {
                  // goodImg = false;
                  // Error message
                  // showMsgBar(iClose, 'Das Bild ist zu groß.', 'Die Dateigröße darf max. 3MB betragen.', red);

               // If image file size is ok
               } else {
                  // goodImg = true;
                  // Distinguish img use cases
                  if( fileInput.id.indexOf('icon') > -1 ) {
                     var imgUsage = 'icon'; // round user icon (for usage in header)
                  } else if ( fileInput.id.indexOf('logo') > -1 ) {
                     var imgUsage = 'logo'; // horizontal logo (contributors/admin or corporation logo)
                  } else if ( fileInput.id.indexOf('photo') > -1 ) {
                     var imgUsage = 'photo'; // photo for posts
                  } // img use cases

   console.log(file, imgUsage); // => the file with all attributes + 'icon'
                  formData.append(imgUsage+'_upload_input', file);
                  formData.append('img-usage', imgUsage);
   console.log(file, imgUsage); // => the file with all attributes + 'icon'
               } // /file size is ok
            } // /file is an image
         } // /file is not empty
      } // /readFile()


      function uploadImg($this, event){

         var serialForm = $this.serialize();
   console.log(serialForm.toString()); // => 'user_id=36'
         $.ajax({
            url        : "test-upload.php",
            type       : "POST",
            data       : formData+serialForm, 
            async      : true,
            cache      : false,
            processData: false,
            contentType: false,
            success    : function(callback){

   console.log(callback);
               formdata = new FormData();
            }
         });
         event.preventDefault();

      } // /uploadImg
   }); // /jQuery

HTML

<!DOCTYPE html>
<html lang="de">
<head>
   <meta charset="utf-8" />
   <title>Test</title>
   <script src="js/jquery-2.1.3.min.js" type="text/javascript"></script>
   <script type="text/javascript">
</head>
<body>
   <h1>Test</h1>

            <form action="" method="post" name="form_profile_icon_upload" class="form form-profile form-upl-img form-profile-side-right" id="form-profile-icon-upload" enctype="multipart/form-data">
               <fieldset class="fieldset icon-upload-fieldset" id="profile-icon-upload-fieldset">
                  <legend class="legend">Icon ändern <span class="label-span">(siehe oben)</span></legend>
                     <input type="file" name="icon_upload_input" class="file-input icon-upload-input" id="profile-icon-upload-input" />
                     <p class="form-txt"><strong>Hinweis:</strong><br />
                        Die Dateigröße darf <strong>3 MB</strong> nicht überschreiten. Quadratische Icons eignen sich optimal, sind aber kein Muss.</p>
                     <input type="hidden" name="user_id" value="36" />
                     <button type="submit" name="profile_icon_upl_btn" class="button button-green form-sbmt-btn" id="profile-icon-upl-btn" value="Hochladen">Hochladen</button>
                     <p class="img-del-txt">
                     </p>
               </fieldset>
            </form><!-- Icon upload form -->


</body>
</html>

PHP 文件如下所示(用于测试目的):

<?php

   if( isset($_POST) && isset($_FILES) ){

print_r($_POST);
echo ($_POST['icon_upload_input']);
print_r($_FILES);
die();

   }

我使用的是最新的 Firefox 35.0 和 jQuery 2.1.3。 谁能帮帮我?

最佳答案

你的问题在data: formData+serialForm,.
FormData 必须单独传递,如果要向其添加数据,请使用构造函数或 append

function uploadImg($this, event){
    var formData  = new FormData($this[0]); //construct the form data with the form
    ... 
    formData.append(imgUsage+'_upload_input', file);
    formData.append('img-usage', imgUsage);
    ...
        data: formData, //just pass the formdata object

关于javascript - 无法将内容附加到 FormData(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28047234/

相关文章:

javascript - scrollIntoView 边缘不平滑

php - 基于 php-mysql 的网站的管理和安全

php - 用于 postgreSQL 的 ssh 隧道

php - 在 jquery 中向表中添加项目

javascript - 扩展 setter 默认对象

Javascript If 语句不计算 True

php - 在 Laravel 5.1 中将对象转换为数组

javascript - 如何正确使用on方法?

jQuery flot 将文本与绘图点关联起来

javascript - 将字符串拆分为数组是特定方式