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

时间:2016-01-08 14:06:51

标签: javascript php angularjs upload ng-file-upload

我正在使用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个创建的属性是unfind,并且只返回:

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);
  }
?>

1 个答案:

答案 0 :(得分:0)

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

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

作为旁注,我会谨慎地允许客户端指定目标文件夹而不进行可靠的验证。攻击者可能能够使用相对路径上传恶意代码。