无法在服务器中打开上传的文件

时间:2019-07-17 09:44:44

标签: javascript php jquery image file-upload

背景

用户上传图片并点击“保存”按钮。

我成功将图像保存在服务器中。我给了777权限到文件夹。...

enter image description here

问题

我试图打开图像,但显示不正确:Image url

enter image description here

HTML

<button class ="save" onclick="test()">Save image to server</button>

脚本

function test(){
var canvas  = document.getElementById("0");
var dataURL = canvas.toDataURL();  // THE BASE 64 DATA
var dataFileName = document.getElementById('fileup').value.replace(/.*(\/|\\)/, ''); // GET THE FILE NAME THAT USER CHOSE
var dataFileType = dataFileName.split('.').pop();

$.ajax({
  type: "POST",
  url: "tamaker.php",
  data: { 
     imgBase64: dataURL,
     imgFileName: dataFileName,
     imgFileType: dataFileType
  }
}).done(function(o, imgFileName) {

  console.log(o);  
  var response = JSON.parse(o);
  console.log(response);

  $('body').prepend('<img src="' + dataFileName+ '" style="height: 200px; width: auto;">');

});
}

save.php

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if( isset($_POST['imgBase64']) && isset($_POST['imgFileName']) && isset($_POST['imgFileType']) ){

    $fname = filter_input(INPUT_POST, 'imgFileName'); // THE FILENAME THE USER CHOSE IS RECEIVED VIA POST
    $img = filter_input(INPUT_POST, 'imgBase64');  // THE BASE64 ENCODING RECEIVED VIA POST
    $imgtype = filter_input(INPUT_POST, 'imgFileType');  // THE FILE TYPE / EXTENSION IS RECEIVED VIA POST

    // STRIP OFF THE BEGINNING OF THE BASE64 DATA, BUT DEPENDS ON THE IMAGE TYPE.  
    // I COULD HAVE SIMPLIFIED THIS BUT USED IF STATEMENTS.
    if ( $imgtype === 'png'){
        $img = str_replace('data:image/png;base64,', '', $img);
    };
    if ( $imgtype === 'jpg' || $imgtype === 'jpeg'){
        $img = str_replace('data:image/jpeg;base64,', '', $img);
    };
    if ( $imgtype === 'gif'){
        $img = str_replace('data:image/gif;base64,', '', $img);
    };

    // REPLACE ALL SPACES IN THE IMAGE DATA WITH PLUS SYMBOL
    $img = str_replace(' ', '+', $img); 
    // CONVERT THE DATA FROM BASE64 ENCODING
    $img = base64_decode($img); 

    // SAVE THE FILE WITH NAME SYNTAX OF:  /images/clientlogos/[ACCOUNT ID]_[FILE NAME]
    file_put_contents('/var/www/html/ecom1/site/test/screen/'.$fname, $img);

    echo "Image has been saved successfully!<p>";
}
?>

这里是pastebin中的完整html代码

2 个答案:

答案 0 :(得分:0)

您应尝试将文件/目录的所有权更改为www-data

要仅针对文件进行更改,请使用:

chown www-data:www-data YOURFILE

要更改目录中的所有文件,请改用以下命令:

chown -R www-data:www-data YOURDIRECTORY/

这为我工作了很多次。

答案 1 :(得分:0)

尝试将您的apache版本更新为2.4。

它为这个家伙带来了成功:https://stackoverflow.com/a/33033946/11722161