Json Ajax和php文件上传

时间:2019-02-19 13:50:04

标签: php json ajax

Hie小组,我需要以下代码的帮助。我想提交带有输入文本和文件字段的表单。 html表单在表单commit上提交数据,然后将数据发送到create_news.php。但该页面未提交图像,并且我无法解码文件字段

<form id="articles_form" method="post" action="" enctype="multipart/form-data">

  <div class="form-group">
    <div class="input-group">
      <input type="text" name="title" placeholder="Enter Title" class="form-control" />
    </div>
  </div>
  <div class="input-group">
    <input type="text" name="date" class="form-control" id="datepicker-autoclose" placeholder="dd/mm/yyyy">
    <span class="input-group-addon"><i class="icon-calender"></i></span>
  </div>


  <div class="form-group">
    <label>Image Cover</label>
    <div class="input-group">
      <input type="file" id="file" placeholder="Article Cover" name="file" class="form-control" />
    </div>
  </div>

  <div class="input-group">
    <div class="input-group">
      <textarea id="editor" required name="content" class="form-control"></textarea>
    </div>
  </div>


  <button type="submit" name="submit" class="btn btn-success">Add New Article
                                        </button>


</form>

Iam使用php,ajax和json ..具有两个页面,其中一个是javascript文件,并将数据发送到php文件进行处理

$(document).on('submit', '#articles_form', function() {

  // get form data
  var form_data = JSON.stringify($(this).serializeObject());

  // submit form data to api
  $.ajax({
    url: 'http://localhost/myzimbiz/admin/process/create_news.php',
    type: "POST",
    contentType: 'application/json',
    data: form_data,
    dataType: 'json', //tell the system the type of data and it is stored in ddata

    success: function(data) {
      //give feedback
      alert(data.message);

      $("#articles_form").trigger('reset'); //reset form


    },
    error: function(xhr, resp, text) {
      // show error to console
      console.log(xhr, resp, text);
    }
  });

  return false;
});

这是我的create_news.php,正在处理上传,我无法解码文件字段。

<?php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");


//include the orm redbean file
include '../db.php';
// get posted data
$data = json_decode(file_get_contents("php://input"));

echo json_encode(array("message" => $data->file->name));

//move file
$stamp = time();
$uploaddir = '../images/';

$save_folder = 'images/';

$uploadfile = $uploaddir . '-' . $stamp . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    $path = $save_folder.'-' . $stamp . basename($_FILES['file']['name']);
} else {
    $path = "images/placeholder.png";
}

if(
    !empty($data->title) &&
    !empty($data->date) &&
    !empty($data->content) &&
    !empty($data->file)
)
{
    R::begin();
    try {
        //set task in database
        $article = R::dispense('about');
        $article->title = $data->title;
        $article->date = $data->date;
        $article->content = $data->content;
        $article->file = $data->file;
        $id = R::store($article);

        // set response code - 201 created
        http_response_code(201);
        // tell the user
        echo json_encode(array("message" => "Created successfully."));
    }
    catch (Exception $e) {
        if ($e->getCode() == 23000) {
            R::rollback();
        }
        echo json_encode(array("message" => "Duplicated data."));
    }

}else{
    // set response code - 503 service unavailable
    http_response_code(503);

    // tell the user
    echo json_encode(array("message" => "Unable to add content."));
}
?>

1 个答案:

答案 0 :(得分:0)

更改:

 var form_data = JSON.stringify($(this).serializeObject());

收件人

var form_data = new FormData($("#articles_form")[0]);

然后设置ajax

<script type="text/javascript">
    $('document').ready(function(){ 
        $('#articles_form').on('submit',function(e){
            e.preventDefault();


            var form_data = new FormData($("#articles_form")[0]);
            form_data.append('file', $('#file')[0].files[0]);

            $.ajax({

                url: 'http://localhost/myzimbiz/admin/process/create_news.php',
                type: "POST",
                data: form_data,
                dataType: 'json',
                encode: true,
                processData: false,
                contentType: false,
                success: function(data) {
                  //give feedback
                  alert(data.message);

                  $("#articles_form").trigger('reset'); //reset form


                },
                error: function(xhr, resp, text) {
                  // show error to console
                  console.log(xhr, resp, text);
                }

            });
        });

    });

服务器。

    <?php
//include the orm redbean file
include '../db.php';
// get posted data

//move file
$stamp     = time();
$uploaddir = '../images/';

$save_folder = 'images/';

$title   = isset($_POST['title']) ? $_POST['title'] : null;
$date    = isset($_POST['date']) ? $_POST['date'] : null;
$content = isset($_POST['content']) ? $_POST['content'] : null;
$file    = isset($_FILES['file']) ? $_FILES['file'] : null;


$uploadfile = $uploaddir . '-' . $stamp . basename($_FILES['file']['name']);


if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    $path = $save_folder . '-' . $stamp . basename($_FILES['file']['name']);
} else {
    $path = "images/placeholder.png";
}
R::begin();
try {
    //set task in database
    $article          = R::dispense('about');
    $article->title   = $title;
    $article->date    = $date;
    $article->content = $content;
    $article->file    = $file;
    $id               = R::store($article);

    // set response code - 201 created
    http_response_code(201);
    // tell the user
    echo json_encode(array(
        "message" => "Created successfully."
    ));
}
catch (Exception $e) {
    if ($e->getCode() == 23000) {
        R::rollback();
    }
    echo json_encode(array(
        "message" => "Duplicated data."
    ));
    http_response_code(503);
}

?>