我開始了這個專案,用我的一點編程技能創建一個社交網路,但我卡住了:我想創建一個像 Facebook / Instagram 這樣的發布系統,但問題是,我希望能夠上傳我的用戶提供的影像直接到服務器而不是資料庫。所以我首先尋找一種我需要預覽影像的方法,為此我使用 JS 將影像轉換為 Base64,然后我將它顯示在我的 img 標簽中。然后用戶可以提交表單,這就是它變得復雜的地方,因為如果我理解正確,您必須將影像轉換為 Blob 由 AJAX 發送,這就是我在 JS 中所做的,除了它到達 PHP 檔案后我找不到將它轉回 Base64 的方法,因為我意識到 PHP 不支持 Blob,或者如果它確實管理它,那么我錯了,而且我還沒有找到在 PHP 中利用這項技術的方法。所以我在這里,發送資料正常,沒問題,但我仍然無法將影像直接上傳到我的服務器,所以我嘗試做一個base64_encode();但它不起作用,然后我嘗試了整個網路上的多個代碼,但它仍然不起作用。我看到在這個站點上有多個問題需要相同的幫助,但在閱讀它們之后,但在實踐中它仍然不起作用,所以希望我能在這里找到一些幫助,我的代碼將起作用。我將代碼留給您,感謝您閱讀所有內容。:) 對不起,我忘記了兩件事,我不想在我的代碼中使用 jQuery,這就是為什么如果你給我 jQuery,我會嘗試翻譯成普通的 JS,但它會相當困難,所以如果你不這樣做請注意,請不要使用 jQuery。第二件事,請原諒我的英語,我是一名對代碼充滿熱情的高中法國人,鑒于整個網站都是英文的,我不允許自己用法語撰寫 :) 我的代碼:
var getHttpRequest = function () {
var httpRequest = false;
if (window.XMLHttpRequest) { //Mozilla,Safari,...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { //IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Abandon :( Impossible de créer une instance XMLHTTP');
return false;
}
return httpRequest;
}
function creapubimg(){
let httpRequest = getHttpRequest();
let content = document.getElementById('content_text_area_img').value;
let imgpub = document.getElementById('chosen-image').src;
let extention = ['jpeg','png','jpg','gif'];
let base64ImageContent,contentType,hashtxt;
var contentTypepost
let idcountforinclude=0;
extention.forEach(element => {
if (imgpub.indexOf(element.value) !== -1){
base64ImageContent = imgpub.replace('data:image/' element.value ';base64');
switch (element.value) {
case 'jpeg':
case 'jpg':
contentTypepost = 2;
contentType = 'image/jpeg'
break;
case 'png':
contentTypepost = 3;
contentType = 'image/png'
break;
case 'gif':
contentTypepost = 1;
contentType = 'image/gif'
break;
default:
break;
}
}
});
let base64 = imgpub.replace('data:image/jpeg;base64,', "");
let blob = b64toBlob(base64,contentType);
let blobUrl = URL.createObjectURL(blob);
hashtxt = makeid(24);
httpRequest.onreadystatechange = function (){
if(httpRequest.readyState === 1){
hide_img_panel_reverse();
}
if(httpRequest.readyState === 2){
// faire apparaitre truc de chargment
}
if(httpRequest.readyState === 4){
if(httpRequest.responseText != 'veuiller remplir tout les champs'){
idcountforinclude = 1;
let docu = document.getElementById('aff_pub');
// hide truc de chargment
let replt = document.createElement('div');
replt.setAttribute('id', idcountforinclude);
docu.prepend(replt);
document.getElementById(idcountforinclude).innerHTML = httpRequest.responseText;
}
}
}
httpRequest.open('POST','includes/createpubimg.php',true);
httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
httpRequest.send("content_publiction=" encodeURIComponent(content) "&img=" encodeURIComponent(blob) "&string=" encodeURIComponent(hashtxt) "&Content-Type=" encodeURIComponent(contentTypepost));
}
function b64toBlob(b64Data, contentType='',sliceSize=512){
let byteCharacters = atob(b64Data);
let byteArrays = [];
for(let offset = 0; offset < byteCharacters.length; offset =sliceSize){
let slice = byteCharacters.slice(offset,offset sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i ) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
let blob = new Blob(byteArrays, {type: contentType});
return blob;
}
這是 PHP :
<?php
include '../database.php';
global $db;
if(isset($_POST['img'])){
if($_POST['Content-Type'] == 1) {
$hashchemin = crypt($_POST['string'], 'piafou');
$hashchemin = rtrim($hashchemin, '/\\');
$chemin = 'img_pub/'.$hashchemin.'.gif';
if(isset($_POST['content_publication'])){
if(!empty($_POST['content_publication'])){
$content = $_POST['content_publication'];
$Blobimg = $_POST['file'];
$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
move_uploaded_file(base64_decode($Base64img), $chemin);
$ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
$ins->execute([
'content' => $content,
'img_pub' => $chemin
]);
$publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
$pub = $publications->fetch();
?>
<div class="aff_pub_div_content" id="<?=$pub['id']?>">
<div style="height: 52px;">
<img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
<label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
<a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
</div>
<div class="nonSelectionnable">
<?php if(!empty($pub['img_pub'])){ ?>
<img src="<?=$pub['img_pub']?>" class="img_pub_aff">
<?php
}
?>
</div>
<div>
<p class="text_pub_aff" id="<?="content_".$pub['id']?>">
<?php
$pub_content = $_POST['content_publication'];
$pub_content = htmlspecialchars($pub_content, ENT_HTML5);
$pub_content = nl2br($pub_content);
echo($pub_content);
?>
</p>
</div>
<div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
<div style="text-align: left;" class="nonSelectionnable">
<ul style="margin-top: 6px; margin-left: 20px">
<?php
$likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
$likepub->execute([
'user' => 16,
'pub' => $pub['id']
]);
if($likepub->rowCount() ==1) {
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: red;
}
</style>
<?php
}
else{
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: white;
}
</style>
<?php
}
?>
<li class="exp_article" style="margin-right: 6px">
<div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
<a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
<img src="IMG/love.png" height="30px" width="30px" id="like">
</a>
</div>
</li>
<li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
<li class="exp_article">
<div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
</li>
</ul>
</div>
</div>
<?php
}
else{
echo('Veuiller remplir tout les champs');
}
}
}
elseif($_POST['Content-Type'] == 2){
$hashchemin = crypt($_POST['string'], 'piafou');
$hashchemin = rtrim($hashchemin, '/\\');
$chemin = 'img_pub/'.$hashchemin.'.jpeg';
if(isset($_POST['content_publication'])){
if(!empty($_POST['content_publication'])){
$content = $_POST['content_publication'];
$Blobimg = $_POST['file'];
$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
move_uploaded_file(base64_decode($Base64img), $chemin);
$ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
$ins->execute([
'content' => $content,
'img_pub' => $chemin
]);
$publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
$pub = $publications->fetch();
?>
<div class="aff_pub_div_content" id="<?=$pub['id']?>">
<div style="height: 52px;">
<img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
<label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
<a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
</div>
<div class="nonSelectionnable">
<?php if(!empty($pub['img_pub'])){ ?>
<img src="<?=$pub['img_pub']?>" class="img_pub_aff">
<?php
}
?>
</div>
<div>
<p class="text_pub_aff" id="<?="content_".$pub['id']?>">
<?php
$pub_content = $_POST['content_publication'];
$pub_content = htmlspecialchars($pub_content, ENT_HTML5);
$pub_content = nl2br($pub_content);
echo($pub_content);
?>
</p>
</div>
<div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
<div style="text-align: left;" class="nonSelectionnable">
<ul style="margin-top: 6px; margin-left: 20px">
<?php
$likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
$likepub->execute([
'user' => 16,
'pub' => $pub['id']
]);
if($likepub->rowCount() ==1) {
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: red;
}
</style>
<?php
}
else{
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: white;
}
</style>
<?php
}
?>
<li class="exp_article" style="margin-right: 6px">
<div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
<a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
<img src="IMG/love.png" height="30px" width="30px" id="like">
</a>
</div>
</li>
<li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
<li class="exp_article">
<div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
</li>
</ul>
</div>
</div>
<?php
}
else{
echo('Veuiller remplir tout les champs');
}
}
}
elseif($_POST['Content-Type'] == 3){
$hashchemin = crypt($_POST['string'], 'piafou');
$hashchemin = rtrim($hashchemin, '/\\');
$chemin = 'img_pub/'.$hashchemin.'.png';
if(isset($_POST['content_publication'])){
if(!empty($_POST['content_publication'])){
$content = $_POST['content_publication'];
$Blobimg = $_POST['file'];
$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
move_uploaded_file(base64_decode($Base64img), $chemin);
$ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
$ins->execute([
'content' => $content,
'img_pub' => $chemin
]);
$publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
$pub = $publications->fetch();
?>
<div class="aff_pub_div_content" id="<?=$pub['id']?>">
<div style="height: 52px;">
<img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
<label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
<a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
</div>
<div class="nonSelectionnable">
<?php if(!empty($pub['img_pub'])){ ?>
<img src="<?=$pub['img_pub']?>" class="img_pub_aff">
<?php
}
?>
</div>
<div>
<p class="text_pub_aff" id="<?="content_".$pub['id']?>">
<?php
$pub_content = $_POST['content_publication'];
$pub_content = htmlspecialchars($pub_content, ENT_HTML5);
$pub_content = nl2br($pub_content);
echo($pub_content);
?>
</p>
</div>
<div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
<div style="text-align: left;" class="nonSelectionnable">
<ul style="margin-top: 6px; margin-left: 20px">
<?php
$likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
$likepub->execute([
'user' => 16,
'pub' => $pub['id']
]);
if($likepub->rowCount() ==1) {
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: red;
}
</style>
<?php
}
else{
?>
<style type="text/css">
.phpdecidelikecolordiv-<?=$pub['id']?>{
background-color: white;
}
</style>
<?php
}
?>
<li class="exp_article" style="margin-right: 6px">
<div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
<a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
<img src="IMG/love.png" height="30px" width="30px" id="like">
</a>
</div>
</li>
<li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
<li class="exp_article">
<div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
</li>
</ul>
</div>
</div>
<?php
}
else{
echo('Veuiller remplir tout les champs');
}
}
}
else{
// message d'erreur
}
}
?>
你可以在我的 PHP 代碼中看到我把這個:
$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
多虧了這行代碼,我相信我會成功地將 blob 轉換為 Base64 如果有人有解決我的問題的方法,我提前感謝他們。PS = 我已經嘗試過使用表單資料,但沒有成功我認為這是解決方案,但我無法讓它作業。感謝所有閱讀的人:)
uj5u.com熱心網友回復:
您不應該使用 base64 進行檔案上傳。對于大檔案,您的 base64 將非常大。盡管 base64 是一種相對有效的二進制資料編碼方式,但平均而言仍會使檔案大小增加 25% 以上。這會增加您的帶寬費用并增加上傳時間。相反,使用表單資料上傳檔案。只需在上傳前使用 base64 預覽檔案。
您也不需要自己實作 XMLHttpRequest(除非您希望您的代碼在 IE 中作業:D),而是使用Fetch API。
<input id="file-upload" type="file" name="file" onchange="readFile()" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<script>
function readFile() {
if(this.files && this.files[0]) {
const fileReader = new FileReader();
fileReader.addEventListener("load", function(e) {
//you can use base64 to preview file
console.log('Base64:', e.target.result);
});
fileReader.readAsDataURL( this.files[0] );
}
}
function uploadFile() {
const formData = new FormData();
const fileUploadInput = document.getElementById('file-upload');
formData.append("file", fileUploadInput.files[0]);
fetch('/upload.php', {
method: "POST",
body: formData
})
.then(() => {
console.log('Success');
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
在 PHP 代碼中,您可以從全域變數中獲取檔案 $_FILES
<?php
// upload.php
var_dump($_FILES['file']);
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401539.html
標籤:javascript php 阿贾克斯
上一篇:如何用ajaxPHP決議陣列
