我正在尝试使用ajax和php上传照片。按照这里的其他答案,应该很简单,但是我无法使其正常工作。谁能看到我的代码有什么问题。

Ajax请求成功,因此我认为它一定是我的php的问题。

我的html代码看起来像这样



<form>
  <input id="upload-input" type="file" multiple="multiple"></br>
  <input class="auction-description" type="text">
  <input class="btn btn-lg submit-images-btn" type="submit">
</form>





我的php代码如下所示:

的PHP

<?php
$dir = "/images";
echo $dir;
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $dir)
?>


和我的js看起来像这样。

js

$('#upload-input').on('change', function() {

  var files = $(this).get(0).files;

  if (files.length > 0) {
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();

    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      fileNames.push(file.name);

      // add the files to formData object for the data payload
      formData.append("image", file);
    }

    $.ajax({
      url: '/uploadphoto.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data) {
        console.log('upload successful!\n' + data);
      }
    });
  }
});

最佳答案

根据我们在聊天中的对话,问题证明您的文件输入未命名,并且是有效的enctype。

它应显示为<input type="file" name="uploaded_file">

并包含enctype="multipart/form-data"和POST方法。

没有“ POST”方法的<form>默认为GET方法。

这些是处理文件时必不可少的/必需的。

参考:


http://php.net/manual/en/features.file-upload.post-method.php

08-06 04:04
查看更多