英文:
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:
<div id="container">
<div id="calendar">
</div>
</div>
<button class="btn btn-dark mb-1" onclick="captureAndSave()">Format</button>
And this JS code:
<script>
function captureAndSave()
{
// Select "calendar" element
var elementToCapture = document.querySelector('section.content');
// Hide ".noPrint" elements
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>
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:
<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>
PHP code called "image.php" that I tried to manage saving to the server without success:
<?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);
?>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论