将新图像文件上传到javascript和php中的图像文件夹的问题

时间:2017-11-28 14:08:31

标签: javascript php html image

我目前正在建立一个网站,我在将图像上传到Cpanel中的图像文件夹时遇到了一些问题。我设法将图像名称保存到我的数据库中,但不保存图像文件。如何将图像文件上传到我的图像文件夹?

我设法在chrome中显示我所有console.log的详细信息。



<!DOCTYPE html>

<html>
<head>
	  <link rel="stylesheet" href="styles.css">
	  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="nav">
    <div class="span10 offset1">
      <form action="#" method="post" name="form_name" id="createform" class="form_class" >
        <div class="control-group">
          <label class="control-label">Facilities Image</label>
          <div class="controls">
             <img id="imgNewUser" height="100">
             <input type="file" name="SelectImg" id="SelectImg" value="My Picture" accept="image/*" onchange="onpreviewFile()">
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn btn-success" id="upload-button" onclick="createfacilities()">Update</button>
        </div>
      </form>
    </div>
      <script>
        function onpreviewFile() {
            var preview = document.querySelector('img'); //selects the query named img
            var file    = document.querySelector('input[type=file]').files[0]; //sames as here
            var reader  = new FileReader();
          
            reader.onloadend = function () {
                preview.src = reader.result;
            }
        
            if (file) {
                reader.readAsDataURL(file); //reads the data as a URL
                uploadFile(); // testing
            } else {
                preview.src = "";
            }
        }
      
        onpreviewFile();
      
        function uploadFile() {
            var file= $('#SelectImg')[0].files;
            console.log("file"+ file);
          
            var formData = new FormData();
            formData.append("fileToUpload", file);
            console.log($('#SelectImg')[0].files[0]);
          
            $('#SelectImg').attr("src", serverURL() + "/images/" + file + "_s");
            console.log("did _s");
          
            var fd = new FormData(document.getElementById("SelectImg"));
            fd.append("label", "WEBUPLOAD");
            console.log("now ajax");
            var url = serverURL + "/upload.php";
          
            $.ajax({
                url: url,
                type: "POST",
                data: fd,
                processData: false,  // tell jQuery not to process the data
                contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
        }
      
        function createfacilities() {
            var image = document.getElementById("SelectImg").files[0].name;
            document.getElementById("createform").submit(); //form submission
            alert("facilities_ID : " + facilities_ID 
                + " \n image : " + image
                + "\n\n Form Submitted Successfully.");
          
            var image = document.getElementById("SelectImg").files[0].name;
            var url = serverURL()+ "/addfacilities.php";
            var JSONObject = {
                "facilities_Img" : image
            };
          
            $.ajax({
                url: url,
                type: 'GET',
                data: JSONObject,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (arr) {
                    _addDescriptionResult(arr);
                },
                error: function () {
                    alert("not okay");
                }
            });
        }
      
        function _addDescriptionResult(arr) {
            document.getElementById("facilities_ID").innerHTML = localStorage.getItem("facilities_ID");
            if (arr[0].result === 1) {
                alert("okay");
            } else {
                alert("not okay 1");
            }
        }
      </script>
    </div>
  </body>
</html>
&#13;
&#13;
&#13;

&#13;
&#13;
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

include("global.php");

try{
	$filename = tempnam('images', '');
	$new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
	unlink($filename);
	
	//print_r($_FILES);
	move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $new_image_name);	
	
	make_thumb("images/" .$new_image_name, "images/" .$new_image_name . "_s", 100);
	
	$json_out = "[" . json_encode(array("result"=>$new_image_name)) . "]";
	echo $json_out;
}
catch(Exception $e) {
	$json_out =  "[".json_encode(array("result"=>0))."]";
	echo $json_out;
}
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。我删除了无关的代码并记录了更改。

其中一个主要问题是你在几个地方调用 serverURL 而没有在任何地方定义它。我删除了这些电话,只是打电话给 upload.php 。您可以根据需要进行更改。

我还将上传目录更改为与PHP文件相同的目录,以保持简单。您可以根据需要进行更改。

大部分代码都是从这里获取的:jQuery AJAX file upload PHP

<强>的index.html

<html>
<head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="nav">
    <div class="span10 offset1">
      <form action="#" method="post" name="form_name" id="createform" class="form_class" enctype="multipart/form-data">
        <div class="control-group">
          <label class="control-label">Facilities Image</label>
          <div class="controls">
             <img id="imgNewUser" height="100">
             <input type="file" name="SelectImg" id="SelectImg" value="My Picture" onchange="onpreviewFile()">
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn btn-success" id="upload-button" onclick="uploadFile()">Update</button>
        </div>
      </form>
    </div>
      <script>
        function onpreviewFile() {
            var preview = document.querySelector('img'); 
            var file    = document.querySelector('input[type=file]').files[0]; 
            var reader  = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file);
                uploadFile(); // don't think you should attempt upload here
            } else {
                preview.src = "";
            }
        }

        function uploadFile() {
            var file_data = $('#SelectImg').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('file', file_data); // The name here ('file') needs to match what PHP is expecting
            alert(form_data);
            $.ajax({
                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function(php_script_response){
                    alert(php_script_response); // display response from the PHP script, if any
                }
             });
        }
      </script>
    </div>
  </body>
</html>

<强> upload.php的

<?php
try{
    if (0 < $_FILES['file']['error']) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    } else {

        $filename = tempnam('images', '');
        $new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
        unlink($filename);

        move_uploaded_file($_FILES['file']['tmp_name'], $new_image_name);

        echo "[" . json_encode(array("result"=>$new_image_name)) . "]";
    }
}
catch(Exception $e) {
    $json_out =  "[".json_encode(array("result"=>0))."]";
    echo $json_out;
}