[英]store image as blob and display on html
我在建立網站時遇到了一個問題。
- 語言:php,js,html
- 數據庫管理系統:mysql
我想做什么
在網站上:
<input id="avatar" type="file" />
const avatar = document.getElementById('avatar');
$.ajax({
url: '../php/action.php',
method: 'POST',
data: `image=${avatar.value}&action=uploadAvatar`
});
class User{
protected $id;
protected $avatar; // blob
// ...
function setId($id) { $this->id = $id; }
function getId() { return $this->id; }
function setAvatar($avatar) { $this->avatar = $avatar; }
function getAvatar() { return $this->avatar; }
// ...
}
function dummy_user($image){
$user1 = new User();
$user1->setAvatar($image);
// ...
}
dummy_user($_POST['image']);
在用戶 class 中, sql
被解析並執行為:
$sql = "INSERT INTO `user` (`id`, `avatar` ...) VALUES ('" . strval($this->getId()) . "', '" . $this->getAvatar() . " ... ')";
// some other values are omitted by ellipsis
// exceptions and error handling are omitted
$stmt = $this->conn->prepare('SELECT * FROM `user` WHERE id = ' . strval($id) . '');
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
$.ajax({
url: '../php/action.php',
method: 'POST',
data: "id=1&action=loadUser"
}).done(function(result){
var res = JSON.parse(result);
console.log(res);
});
我明白了:
{"id":"1","avatar":"C:fakepathhusky.png" ...}
有幾件事值得一提:
數據庫用戶表頭像字段設置為blob。 上傳前初始圖片大小為349kb
上傳到數據庫后,blob 為19b
圖片名稱: husky.png
// result collected from php by ajax
var res = JSON.parse(result);
let img = document.createElement('img');
img.setAttribute('src', 'data:image/png;base64,' + btoa(res.avatar));
我以失敗告終。 預期的結果是在 html 頁面中顯示圖像。 任何建議將不勝感激。
不能上傳帶有Ajax的文件,只能通過formdata上傳帶有Ajax的文件
使用表單標簽包裝您的文件輸入,如下所示:
<form id="avatar">
<input name="image" type="file" />
</form>
像這樣重寫您的 Ajax 代碼:
const form = document.getElementById('avatar');
const formdt = new FormData(form);
$.ajax({
url: '../php/action.php',
method: 'POST',
data: formdt,
processData: false,
contentType: false
})
也許這會有所幫助。 這是將圖像作為 blob 存儲在 mysql 中並顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.