[英]Convert local image blob to base64, in PHP
我正在為內部工具編寫(HTML)表單。 用戶可以填寫有關問題的數據並附加屏幕截圖。 然后將此表單通過Ajax提交給PHPMailer進行發送。 問題出在截圖上。 由於系統限制,我無法讓用戶實際將文件上傳到服務器。
目前,我正在使用HTML5文件閱讀器來選擇文件。 然后,我將圖像Blob轉換為base64,並將其發送到PHPMailer,以轉換為附件。 這實際上工作得很好。 但是,我遇到了文件大小問題。 具體來說就是1000px x 1000px(402KB)的測試圖像。 所得的base64字符串長度超過一百萬個字符,並且請求返回413(請求實體太大) 。
我知道base64並不是傳輸大型圖像的有效方法,並且我已經看到有關從數據庫檢索/轉換圖像斑點的各種文章。 我找不到的是有關檢索本地圖像Blob並將其轉換為base64的信息。
我的圖片Blob網址如下所示:Blob: http : //example.com/18960927-e220-4417-93a4-edb608e5b8b3
是否有可能在PHP中獲取此本地圖像數據,然后將其轉換為base64?
我無法發布很多源代碼,但是以下內容將使您了解我如何使用FileReader
window.onload=function(){
window.URL = window.URL || window.webkitURL;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
}
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
fileList.innerHTML = "";
var list = document.createElement("ul");
fileList.appendChild(list);
for (var i = 0; i < files.length; i++) {
if(files[i].size > 1000000) {
alert(files[i].name + ' is too big. Please resize it and try again.');
} else {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);
img.height = 60;
img.setAttribute("class", "shotzPrev");
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + "<br>" + files[i].size + " bytes";
li.appendChild(info);
}
}
}
}
您可以POST
的File
對象php
fetch("/path/to/server", {
method: "POST"
body: files[i]
})
.then(response => console.log(response.ok))
.catch(err => console.error(err));
我認為它的nginx錯誤,請更改nginx.conf文件中的client_max_body_size值。
例如 :
# set client body size to 2M #
client_max_body_size 2M;
PHP配置(可選)
您的php安裝也限制了上傳文件的大小。 編輯php.ini並設置以下指令。
;This sets the maximum amount of memory in bytes that a script is allowed to allocate
memory_limit = 32M
;The maximum size of an uploaded file.
upload_max_filesize = 2M
;Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize
post_max_size = 3M
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.