一般上傳圖片到服務(wù)器有兩種方式:
1、把圖片轉(zhuǎn)換成二進(jìn)制直接存儲(chǔ)到數(shù)據(jù)庫里
2、把圖片存儲(chǔ)到本地目錄,并將圖片地址存儲(chǔ)到數(shù)據(jù)庫里
先粗淺地談下我對(duì)這兩種存儲(chǔ)方法的優(yōu)劣點(diǎn)的認(rèn)識(shí):
1、把圖片轉(zhuǎn)換成二進(jìn)制直接存儲(chǔ)到數(shù)據(jù)庫的優(yōu)點(diǎn)是有利于數(shù)據(jù)的備份和遷移,但缺點(diǎn)就是會(huì)影響數(shù)據(jù)讀寫速率。一般大圖、多圖不建議用此方式,一般存儲(chǔ)用戶頭像、富文本內(nèi)容存儲(chǔ)時(shí)可以應(yīng)用此方式。
2、將圖片存儲(chǔ)到本地目錄,在數(shù)據(jù)庫上只存儲(chǔ)圖片路徑的優(yōu)點(diǎn)是有利于數(shù)據(jù)的讀寫,畢竟存一個(gè)地址要比存整個(gè)圖片的大小要小得多。但是缺點(diǎn)就不利于數(shù)據(jù)的備份和遷移。
先介紹一下存儲(chǔ)圖片路徑的方法:
html代碼:
<form id="form1"> <span style="white-space:pre;"> </span><div class="bookImg"> <div class="img-box"> <input type="file" name="photo1" id="" title="文件不超過200kb,大小最佳為60*60"> </div> <div class="img-box"> <input type="file" name="photo2" id="" title="文件不超過200kb,大小最佳為60*60"> </div> </div> <input type="button" class="bookBtn btnBlue" id="publishBook" value="發(fā)布圖書" onclick="fsubmit()"/> </form>
ajax請(qǐng)求:
function fsubmit() { var form1=document.getElementById("form1"); var fd =new FormData(form1); $.ajax({ url: "photo.php", type: "POST", data: fd, processData: false, contentType: false, success: function(response,status,xhr){ console.log(xhr); var json=$.parseJSON(response); var result = ''; result += '<br/><img src="' + json['photo1'] + '" height="100" />'; result += '<br/><img src="' + json['photo2'] + '" height="100" />'; result += '<br/>' + json['photo1']; result += '<br/>' + json['photo2']; $('#result').html(result); } }); return false; }
php代碼:photo.php
<?php require('conn.php'); $nameTag = time(); $filename1 = $nameTag . '0' . substr($_FILES['photo1']['name'], strrpos($_FILES['photo1']['name'],'.')); $filename2 = $nameTag . '1' . substr($_FILES['photo2']['name'], strrpos($_FILES['photo2']['name'],'.')); $response = array(); $path1 = "img/" . $filename1; <span style="color:#ff0000;">//注意要在目錄下新建一個(gè)名為img的文件夾用來存放圖片 $path2 = "img/" . $filename2; if(move_uploaded_file($_FILES['photo1']['tmp_name'], $path1) && move_uploaded_file($_FILES['photo2']['tmp_name'], $path2) ){ $response['isSuccess'] = true; $response['photo1'] = $path1; $response['photo2'] = $path2; }else{ $response['isSuccess'] = false; } echo json_encode($response); ?>
數(shù)據(jù)庫表我就不貼了,存圖片地址,字段類型直接用字符型就可以了。
現(xiàn)在在介紹一下把圖片轉(zhuǎn)換成二進(jìn)制直接存進(jìn)數(shù)據(jù)庫的方法:
這里我沒有用ajax請(qǐng)求,直接用表單的post 請(qǐng)求提交數(shù)據(jù)
html代碼:
<form action="photo.php"> <span style="white-space:pre;"> </span><div class="pic"> <input type="file" name="photo" id="" title="文件不超過200kb,大小最佳為60*60" onchange="imgPreview(this)">上傳頭像 </div> </form>
php代碼:photo.php
<?php require('conn.php'); $image = mysql_real_escape_string(file_get_contents($_FILES['photo']['tmp_name'])); $sqlstr = "insert into user(photo) values('".$image."')"; @mysql_query($sqlstr) or die(mysql_error()); exit(); ?>
這樣就把圖片轉(zhuǎn)換成二進(jìn)制并儲(chǔ)存進(jìn)數(shù)據(jù)庫了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選