Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

javascript - 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. The code I'm using is below:

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
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

question from:https://stackoverflow.com/questions/66065459/trying-to-send-file-to-webserver-from-webpage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured out the problem.

It was a permissions issue but it was to do with the user that was running the php service.

Once this was changed to the correct user the script ran as expected.

Thanks for the help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...