php 带文件上传的表单(可选文件上传)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 带文件上传的表单(可选文件上传)相关的知识,希望对你有一定的参考价值。

<?php
// require DB config + constants
require "dbconfig.php";  

if($_SERVER['REQUEST_METHOD'] == 'POST') { 

	echo 'POST ARRAY<pre>';
	print_r($_POST); 
	echo '</pre>';
	echo "<br>====================<br>";

	echo 'FILES ARRAY<pre>';
	print_r($_FILES); 
	echo '</pre>';
	echo "<br>====================<br>";

	echo 'Detailed info:<br>';
	echo $_FILES['filelogo']['name']  . '<br>' ;
	echo $_FILES['filelogo']['type'] . '<br>' ;
	echo $_FILES['filelogo']['tmp_name'] .'<br>' ;
	echo $_FILES['filelogo']['error'] .'<br>' ;
	echo $_FILES['filelogo']['size'] .'<br>' ;

// exit;

	try {
		$db = new PDO($dsn, $username, $password);

		// specify the directory 
		$targetDir = "fileuploads/";

		// Allow only these extensions
		$allowed = ['gif','png', 'jpg'] ;



		// POST values
		$name = $_POST['name'] ;
		$email = $_POST['email'] ;
		$file_name = '' ;
		// if user didnt provide file to upload
		if ( $_FILES['filelogo']['name'] != ''   ) {
			$file_name = $_FILES['filelogo']['name']; // cherry_blossom.jpg
			$targetFile = $targetDir.$file_name;  // fileuploads/cherry_blossom.jpg 
			// Get the extension name
			$extension = explode('.', $_FILES['filelogo']['name'] ) ;
			$extension = strtolower(end($extension) ) ;	
			if( in_array($extension, $allowed )  ) {
				move_uploaded_file( $_FILES['filelogo']['tmp_name'] ,  $targetFile ); 
			}
			else {
				echo "<h2>Errors uploading file:</h2> ";
				echo $_FILES['filelogo']['error']; 
				exit;
			}
		}


		//insert data form, with file_name(optional, default=NULL)

	    $query = 'INSERT INTO singleupload (  name, email, file_name, dateuploaded  )
	              VALUES  ( :name, :email, :file_name, :dateuploaded ) ';
	    $statement = $db->prepare($query);
	    $statement->bindValue(':name', $name );
	    $statement->bindValue(':email', $email );
	    $statement->bindValue(':file_name', $file_name );
	    $statement->bindValue(':dateuploaded', date("Y-m-d H:i:s") );
	    // $statement->execute(); 
	    $statement->execute() or die(print_r( $statement->errorInfo(), true) );
	    echo '<h2>FILE INSERT SUCCESSFUL</h2>';
	    $statement->closeCursor();


	

	} catch (PDOException $e) {
		// print trace
	    $error_message = $e->getMessage();
	    exit();
	}

}


?>



<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title></title>

	<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
	<!--[if IE]>
		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
</head>
<body>
 
<form method="post" action="" enctype="multipart/form-data">
	<div><input type="text" name="name" placeholder="Full Name"></div>
	<div><input type="text" name="email" placeholder="Email"></div>
	<div><input id="filelogo" type="file" name="filelogo"></div>
	<p><br></p>
	<img id="showimage" src="" height="200" alt="Image preview...">  
	<input type="submit" value="SUBMIT"> 
</form>


</body>



<script>


$("#filelogo").change(function() {
	var preview = document.querySelector('#showimage');
	var file    = document.querySelector('input[type=file]').files[0];
	var reader = new FileReader();

	// console.log(file) ;	
	
    if( $('#filelogo').val() !=""){
	    // readURL function is redundant so we just use reader.onload if the file size is less than 1MB
	    // 'this'  refers to the current file object
	     // check if file size is greater than 1MB OR file is not an image
        if (file.size>=1000000  ) {
	        alert("File upload limit is 1MB ") ;
        }

        else if ( file['type'].split('/')[0] !='image' ) {
        	alert('File is not an image, only [gif,png, jpg]  are allowed') ;
        }

        else {  
	        
			reader.addEventListener("load", function () {
			    preview.src = reader.result;
			}, false);	        
	           
        
			if ( file ) {   reader.readAsDataURL(file);    }
			   
        }   

    }
    
    /* optional
	   triggers when a file selection is cancelled or there is no image currently selected
    */

    /*
    else {
	    // 
	    console.log("File selection cancelled, loading default placeholder.png") ;
	    $('#showimage').attr('src','https://regigo.com/beta/organizer/images/placeholder.png');
	}  
	*/
    
    
    

});



</script>


</html>






================== DATABASE SCHEMA ===========================

Field           Type	        NULL    KEY    Default    Extra
------------------------------------------------------------------------
id              int(11)         NO      PRI    NULL       auto_increment
name            varchar(100)    NO             NULL
email           varchar(100)    NO             NULL
file_name       varchar(100)    NO             NULL
dateuplaoded    date            NO             NULL

以上是关于php 带文件上传的表单(可选文件上传)的主要内容,如果未能解决你的问题,请参考以下文章

PHP多文件上传格式化

php上传文件为啥一定要用post

OkHttp初探3:简单文件上传表单文件一起上传带进度条的文件上传MediaType介绍。Kotlin版本

使用ajax上传表单(带文件)

PHP:检查动态添加的文件上传是不是为空

[Layui]上传文件带进度条+表单提交功能优化