需求
手机/PC需要发送文本内容到手机/PC上, 使用webserver转达方式, 无需下载软件, 登录账号, 一次布置, 终生适用…
环境
● WebServer环境(此处使用PHPStudy)
● Google Chrome浏览器
● 同一个路由 或 iSH 手机分享热点下的设备(布置在外网, 无此限制)
表现
(注: 二维码会违规, 故不显示)
实现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file + `?=${Date.now()}`, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
var node = document.getElementById('output');
if (!node) {
node = document.createElement('div');
document.body.appendChild(node);
}
node.innerText = allText;
}
}
}
rawFile.send(null);
}
function onSubmit() {
var form = document.forms.myform;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if (e.id == "textValue") {
console.log(e.value);
}
}
}
function getLinkParams() {
let paramsData = {};
let str = document.location.href;
if (str) {
console.log(str);
//解析链接参数
str = decodeURI(str);
let whIndex = str.indexOf("?");
if (whIndex != -1) {
let param = str.slice(whIndex + 1).split("&");
let strArr;
for (let i = 0; i < param.length; i++) {
strArr = param[i].split("=");
paramsData[strArr[0]] = strArr[1];
}
}
}
return paramsData;
}
</script>
<form action="save.php" method="post" id="myform">
<fieldset>
<legend>手机PC文本传输</legend>
<label id="ctxs">要传输的文本: <textarea name="content" id="textValue" cols="30" rows="10"></textarea> </label><br /><br />
<input type="submit" formtarget="_blank" onclick="onSubmit()" />
</fieldset>
</form>
<br /><br />
<script>
let params = getLinkParams();
let txtParam = params['filename'];
readTextFile(txtParam || 'content');
if(txtParam) {
let input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', 'filename');
input.setAttribute('value', txtParam);
let label = document.getElementById('ctxs');
label.appendChild(input);
}
</script>
</body>
</html>
save.php
<?php
$fileName = '';
if($_POST['filename']) {
$fileName = $_POST['filename'];
} else {
$fileName = "content";
}
$contents = $_POST['content'];
$fileNameWithPath = $fileName;
if(file_put_contents($fileNameWithPath, $contents)){
echo "File ". basename($fileNameWithPath) ." was successfully created.";
} else{
echo "Failed to create file";
}
?>
部署
将 index.html, save.php 放到 PHPStudy 的 WWW/input 目录下(input目录名自取)
使用
● 不指定文件名打开链接, 默认文本都存储在 content 文件中
http://192.168.2.129/input/index.html
● 指定文件名, 文本存储在指定文件名xxx内
http://192.168.2.129/input/index.html?filename=xxx