这是我第一次尝试上传图片到数据库。我有下面的代码来上传图片到mysql database.But没有图片被上传到database.No错误或警告已经给出。
php:
if(isset($_FILES['files'])){
$name=$_FILES['files']['name'];
if(!empty($name)){
if(!file_exists($name)){
$temp=$_FILES['files']['tmp_name'];
//move_uploaded_file($temp,getcwd().'/uploads/'.$name);
try{
$servername='localhost';
$username='root';
$password='';
$dbname='login';
$fp = fopen($temp, 'r');
$conn=new PDO('mysql:host=localhost;dbname=login',$username,$password);
$stmt = $conn->prepare("INSERT INTO images (image_name, image) VALUES (?, ?)");
$stmt->bindParam(1, $_FILES['file']['name']);
$stmt->bindParam(2, $fp, PDO::PARAM_LOB);
if($stmt->execute()){
echo 'its uploaded to database';
}
}catch(PDOException $e){
echo $e->getMessage();
}
}else{
echo 'file already exists';
}
}
}else{
echo 'select a file';
}HTML和js:
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<style>
#mydiv{
position: relative;
overflow: hidden;
width:80px;
height:30px;
background:crimson;
color:white;
text-align:center;
padding:auto;
border-radius:4px ;
border:1px solid black;
font-size:22px;
}
#files{
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
</head>
<body>
<form action='file.php' method='POST' enctype='multipart/form-data'>
<div id='mydiv'>upload
<input type="file" id="files" name="files" multiple />
</div>
<input type='submit' value='submit' name='submit'>
</form>
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
console.log(theFile.type);
var div = document.createElement('div');
div.setAttribute('style','width:300px;height:300px;border:1px solid black;position:relative;');
div.innerHTML = ['<img style="width:300px;height:300px;" class="thumb" src="',e.target.result,
'" title="',escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(div, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>发布于 2015-09-14 02:54:42
检查PHP代码,很可能是$stmt->execute()执行失败。
在PHP文档(http://php.net/manual/en/pdo.lobs.php)中,你需要在'rb‘模式下打开你的镜像:
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
为了将其插入到数据库
https://stackoverflow.com/questions/32553316
复制相似问题