[英]Converting file upload to binary, post to server and save file using PHP
我正在使用無法將文件發布到服務器的應用程序。 因此,我選擇將其作為字符串發送到服務器,然后使用PHP將其重新制作為文件。 以下是我用來將圖像轉換為字符串的JavaScript代碼。
var file = document.getElementById("fileForUpload").files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (evt) {
document.getElementById("fileContents").value = utf8_to_b64(evt.target.result);
}
reader.onerror = function (evt) {
document.getElementById("fileContents").value = "error reading file";
}
}
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
在服務器端,我正在這樣做
header("Content-type: image/png");
$data = preg_replace('/\s+/', '', $data);
echo base64_decode($data);
exit;
但是它說圖像無法顯示,因為它包含錯誤。
您能告訴我我在做什么錯嗎? 我正確地將Base64編碼的字符串接收到服務器。
編輯
請注意,我正在嘗試通過HTML表單發布字符串。
簡單:
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.