Angular + PHP 文件上传(无法发送新创建的属性)

Angular + PHP file upload (can't sent newly created properties)

我正在使用 ng-file-upload . 它工作得很好,但我需要向我发送的对象添加一些特定的属性。这里的控制器方法:

self.uploadFiles = function (files) {
  if (files && files.length) {
    for (var i = 0; i < files.length; i++) {
      files[i].upload_folder = 'upload'; //here i add first property
      files[i].current_date = getCurrentDate(); //here second
      var file = files[i];
      console.log(files[i]);
      Upload.upload({
        url: 'app/views/antonovich/upload.php',
        headers: {'Content-Type': undefined},
        method: 'POST',
        data: file,
        file: file
      }).progress(function(evt){
        self.uploadProgress = parseInt(100.0 * evt.loaded / evt.total);
        //console.log('progress: ' + self.uploadProgress + '% ' + evt.config.file.name);
      }).success(function(data, status, headers, config){
        console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
        $('.errors').html(data);
        self.uploadReady = config.file.name + ' uploaded.';
      });
    }
  }
}

在控制台日志中我看到了该属性,例如:

File {$$hashKey: "object:19", upload_folder: "upload", current_date: "2016-01-08"}
$$hashKey: "object:19"
current_date: "2016-01-08"
file: File
lastModified: 1448878298580
lastModifiedDate: Mon Nov 30 2015 13:11:38 GMT+0300 (Russia Standard Time)
name: "14488072165280.png"
size: 872713
type: "image/png"
upload_folder: "upload"
webkitRelativePath: ""
__proto__: File

PHP 脚本将这些文件上传到文件夹并创建数据库行,但是 2 个创建的属性未定义,return 就是这样:

Response: Array
(
    [name] => 14488072165280.png
    [type] => image/png
    [tmp_name] => C:\wamp\tmp\phpC39D.tmp
    [error] => 0
    [size] => 872713
)

此处 php 脚本示例:

<?php
  if(isset($_FILES['file'])) {
    print_r($_FILES['file']);
    $errors= array();

    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_type = $_FILES['file']['type'];
    $upload_folder = $_FILES['file']['upload_folder'];
    $current_date = $_FILES['file']['current_date'];
    print_r($upload_folder);
    print_r($current_date);

    $db = new PDO('mysql:host=localhost;dbname=antonovich', 'root', '');
    $query = "INSERT INTO  portfolio(url,date) VALUES('$file_name','$current_date')";
    $stmt = $db->prepare($query);
    $stmt->execute();

    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    move_uploaded_file($file_tmp,"../../img/".$upload_folder."/".$file_name);
    echo $file_name . " uploaded file: " . "images/" . $file_name;

  }
  else {
    $errors= array();
    $errors[]="No image found";
    print_r($errors);
  }
?>

有关背景,请参阅 PHP documentation on file uploads。 $_FILES 超全局仅包含有关每个上传文件的一组固定值(nametypetmp_nameerrorsize),任何其他来自 POST 请求的数据应该在 $_POST 超全局中。尝试像这样更改您的 PHP 脚本:

$upload_folder = $_POST['upload_folder'];
$current_date = $_POST['current_date'];

附带说明一下,我对允许客户在未经可靠验证的情况下指定目标文件夹持谨慎态度。攻击者可能能够使用相对路径上传恶意代码。