如何在PHP中将图像保存到服务器文件夹?

huangapple go评论86阅读模式
英文:

How to save an image to a server folder in PHP?

问题

我有这段HTML代码:

<div id="container">
  <div id="calendar">
  </div>
</div>
<button class="btn btn-dark mb-1" onclick="captureAndSave()">Format</button>

还有这段JS代码:

<script>

function captureAndSave() 
{
  // 选择 "calendar" 元素
  var elementToCapture = document.querySelector('section.content');

  // 隐藏 ".noPrint" 元素
  var elementsToHide = elementToCapture.querySelectorAll('.noPrint');
  elementsToHide.forEach(function(element)
  {
    element.style.visibility = 'hidden';
  });

  html2canvas(elementToCapture).then(function(canvas) 
  {
    var imageBase64 = canvas.toDataURL('image/png');

    elementsToHide.forEach(function(element) 
    {
      element.style.visibility = 'visible';
    });

    var link = document.createElement('a');
    link.href = imageBase64;
    link.download = 'captura.png';

    link.click();
  });
}

</script> 

按下按钮应该下载 "section.content" 内容的图像,对吗?实际上,这个操作确实执行了,但当尝试修改这段代码,使其将图像下载到服务器文件夹而不是下载到用户的计算机时,我做不到。

我尝试了以下方法:

<script>

function captureAndSave() 
{
  var elementToCapture = document.querySelector('section.content');

  var elementsToHide = elementToCapture.querySelectorAll('.noPrint');
  elementsToHide.forEach(function (element) {
    element.style.visibility = 'hidden';
  });

  html2canvas(elementToCapture).then(function (canvas) {
    var imageBase64 = canvas.toDataURL('image/png');

    elementsToHide.forEach(function (element) {
      element.style.visibility = 'visible';
    });

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'assets/imagen.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    var data = 'image=' + encodeURIComponent(imageBase64);
    xhr.send(data);

    xhr.onload = function () {
      if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        if (response.success) {
          alert(response.message);
        } else {
          alert('Error: ' + response.message);
        }
      }
    };
  });
}

</script>

我尝试通过名为 "image.php" 的PHP代码来保存到服务器,但没有成功:

<?php
$response = array();

if(isset($_POST['image'])) 
{
  $imageData = $_POST['image'];

  $filePath = '../vistas/img/temp/imagen.png';

  if(file_put_contents($filePath, base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData)))) 
  {
    $response['success'] = true;
    $response['message'] = 'The image has been saved successfully.';
  } 
  else 
  {
    $response['success'] = false;
    $response['message'] = 'There was an error saving the image.';
  }
} 
else 
{
  $response['success'] = false;
  $response['message'] = 'No image received.';
}

header('Content-type: application/json');
echo json_encode($response);
?>

对于我想要实现的目标,您有什么建议或更好的方法吗?首先,感谢您。

英文:

I have this HTML code:

 &lt;div id=&quot;container&quot;&gt;
   &lt;div id=&quot;calendar&quot;&gt;
   &lt;/div&gt;
 &lt;/div&gt;
&lt;button class=&quot;btn btn-dark mb-1&quot; onclick=&quot;captureAndSave()&quot;&gt;Format&lt;/button&gt;

And this JS code:

 &lt;script&gt;

  function captureAndSave() 
  {
    // Select &quot;calendar&quot; element
    var elementToCapture = document.querySelector(&#39;section.content&#39;);

    // Hide &quot;.noPrint&quot; elements
    var elementsToHide = elementToCapture.querySelectorAll(&#39;.noPrint&#39;);
    elementsToHide.forEach(function(element)
    {
      element.style.visibility = &#39;hidden&#39;;
    });

    html2canvas(elementToCapture).then(function(canvas) 
    {
      var imageBase64 = canvas.toDataURL(&#39;image/png&#39;);

      elementsToHide.forEach(function(element) 
      {
        element.style.visibility = &#39;visible&#39;;
      });

      var link = document.createElement(&#39;a&#39;);
      link.href = imageBase64;
      link.download = &#39;captura.png&#39;;

      link.click();
    });
  }

&lt;/script&gt; 

Pressing the button is supposed to download an image of the content "section.content", right? Well, this action is actually carried out, but when trying to adapt this code and make it download the image to a server folder instead of being downloaded to the user's computer, I can't do it.

I tried this approach:

&lt;script&gt;

function captureAndSave() 
{
  var elementToCapture = document.querySelector(&#39;section.content&#39;);

  var elementsToHide = elementToCapture.querySelectorAll(&#39;.noPrint&#39;);
  elementsToHide.forEach(function (element) {
    element.style.visibility = &#39;hidden&#39;;
  });

  html2canvas(elementToCapture).then(function (canvas) {
    var imageBase64 = canvas.toDataURL(&#39;image/png&#39;);

    elementsToHide.forEach(function (element) {
      element.style.visibility = &#39;visible&#39;;
    });

    var xhr = new XMLHttpRequest();
    xhr.open(&#39;POST&#39;, &#39;assets/imagen.php&#39;, true);
    xhr.setRequestHeader(&#39;Content-type&#39;, &#39;application/x-www-form-urlencoded&#39;);

    var data = &#39;image=&#39; + encodeURIComponent(imageBase64);
    xhr.send(data);

    xhr.onload = function () {
      if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        if (response.success) {
          alert(response.message);
        } else {
          alert(&#39;Error: &#39; + response.message);
        }
      }
    };
  });
}

&lt;/script&gt;

PHP code called "image.php" that I tried to manage saving to the server without success:

&lt;?php
$response = array();

if(isset($_POST[&#39;image&#39;])) 
{
  $imageData = $_POST[&#39;image&#39;];

  $filePath = &#39;../vistas/img/temp/imagen.png&#39;;

  if(file_put_contents($filePath, base64_decode(preg_replace(&#39;#^data:image/\w+;base64,#i&#39;, &#39;&#39;, $imageData)))) 
  {
    $response[&#39;success&#39;] = true;
    $response[&#39;message&#39;] = &#39;The image has been saved successfully.&#39;;
  } 
  else 
  {
    $response[&#39;success&#39;] = false;
    $response[&#39;message&#39;] = &#39;There was an error saving the image.&#39;;
  }
} 
else 
{
  $response[&#39;success&#39;] = false;
  $response[&#39;message&#39;] = &#39;No image received.&#39;;
}

  header(&#39;Content-type: application/json&#39;);
  echo json_encode($response);
?&gt;

Any suggestions on what I could change or a better approach to what I want to achieve? First of all, Thanks.

答案1

得分: 1

一件引起我的注意的事情是您的$filePath变量所定义的路径。如果您要上传文件的完整目录树不存在,写操作将失败。

您可以使用以下代码来确保目录树一直到要写入的文件存在,然后再尝试进行写入:

$directory = dirname($filePath);
if (!is_dir($directory)) {
    mkdir($directory, 0777, true);
}

您还可以使用异常处理来确定错误原因,用于调试目的。默认情况下,file_put_contents在这种情况下只会返回一个警告,所以让PHP 抛出异常可能超出了您项目的范围。

检查您的PHP日志也可以帮助您追踪问题。

英文:

One thing that jumped me is the path defined for your $filePath variable. If the full directory tree where you want to upload your file doesn't exist, the write operation will fail.

You can use the following code to make sure the directory tree up to the file you want to write to exists, before attempting to write to it:

$directory = dirname($filePath);
if (!is_dir($directory)) {
    mkdir($directory, 0777, true);
}

You can also use exception handling to determine what the error is, for debugging purposes. By default, file_put_contents only returns a warning in this situation, so getting PHP to throw exceptions instead may be beyond the scope of your project.

Checking your PHP logs can also help you track down the issue.

huangapple
  • 本文由 发表于 2023年7月18日 04:39:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定