简体   繁体   English

尝试从网页向网络服务器发送文件

[英]Trying to send file to webserver from webpage

I am trying to send some text from my webpage to a webserver and save it within a file but I can't seem to get it working and I don't have any errors being produced to tell me why.我正在尝试将一些文本从我的网页发送到网络服务器并将其保存在一个文件中,但我似乎无法让它工作,而且我没有产生任何错误来告诉我原因。

I'm trying to use JavaScript to send a post request to the server and then have the PHP process the request and save the contents into a file.我正在尝试使用 JavaScript 向服务器发送发布请求,然后让 PHP 处理请求并将内容保存到文件中。 The code I'm using is below:我正在使用的代码如下:

JavaScript JavaScript

function sendCode() {
    const copyCode = document.getElementById("terraCode").textContent;
    const textArea = document.createElement('textarea');
    textArea.textContent = copyCode; //The text being sent
    
    var code = new FormData();
    code.append("code", copyCode);
    var xhr = new XMLHttpRequest();
    xhr.open('post', './test.php', true); //Request and location of PHP
    xhr.send(code);
    
}

document.getElementById("TestCode").addEventListener("click", sendCode); //Execute function above based on button click

PHP PHP

<?php
if (!empty($_POST['code'])) {
    $data = $_POST['code'];
    $fname = "test" . ".tf"; //generates file name

    $file = fopen("./file" . $fname, 'w'); //creates new file
    fwrite($file, $data);
    fclose($file);
}
?>

I am pretty confident it is getting the text correctly as it is present when I check inspect element on the page, but nothing seems to be happening server side and I'm not sure if the data is even reaching the server.当我检查页面上的检查元素时,我非常有信心它可以正确获取文本,但服务器端似乎没有发生任何事情,我不确定数据是否到达服务器。

Can anyone explain why this wouldn't be working?谁能解释为什么这不起作用?

Edit: I'm running an Nginx web server and PHP7.4 is installed and enabled on the server编辑:我正在运行 Nginx web 服务器,并且在服务器上安装并启用了 PHP7.4

I figured out the problem.我解决了这个问题。

It was a permissions issue but it was to do with the user that was running the php service.这是一个权限问题,但它与运行 php 服务的用户有关。

Once this was changed to the correct user the script ran as expected.一旦将其更改为正确的用户,脚本就会按预期运行。

Thanks for the help.谢谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM