簡體   English   中英

將圖像存儲為 blob 並在 html 上顯示

[英]store image as blob and display on html

我在建立網站時遇到了一個問題。

  • 語言:php,js,html
  • 數據庫管理系統:mysql

我想做什么

  1. 從存儲為用戶記錄中的 blob 的數據庫加載用戶頭像(圖像)
  2. 讓它顯示在我的 html 網頁上

在網站上:

  1. 用戶上傳圖片作為頭像是通過
<input id="avatar" type="file" />
const avatar = document.getElementById('avatar');

$.ajax({
    url: '../php/action.php',
    method: 'POST',
    data: `image=${avatar.value}&action=uploadAvatar`
});
  1. 在用戶 class
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; }
    // ...
}
  1. 頭像僅在創建記錄時存儲。 哪個用戶只能在注冊時設置頭像。
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 

  1. 從數據庫加載記錄
// 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);
  1. 但是,對於在 javascript 中收集的結果
$.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

  1. 將圖像渲染到 html 頁面
// 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM