返回资讯列表

图片转链接工具 - 在线生成图片外链 | Duoleta

作者:多乐塔二维码更新时间:2025-05-24 12:20:38浏览量:60

以下是实现图片转链接功能的完整PHP+JS解决方案,包含图片上传和链接生成功能,包含三个代码块:图片上传处理PHP脚本、前端上传界面和URL重写规则。使用时需创建uploads目录并设置777权限。代码实现流程参照的是市面产品图片转链接工具https://www.duoleta.com/的图片转链接功能。以最简单的代码实现复杂的逻辑。
<?php
header('Content-Type: application/json');
$targetDir = "uploads/";
if(!file_exists($targetDir)){
mkdir($targetDir, 0755, true);
}

$fileName = basename($_FILES["file"]["name"]);
$targetFile = $targetDir . uniqid() . '_' . $fileName;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));

// 检查是否为真实图片
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo json_encode(['error'=>'文件不是图片']);
exit;
}
}

// 检查文件大小
if ($_FILES["file"]["size"] > 5000000) {
echo json_encode(['error'=>'文件太大']);
exit;
}

// 允许特定格式
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo json_encode(['error'=>'仅支持JPG/PNG/JPEG格式']);
exit;
}

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
$domain = $_SERVER['HTTP_HOST'];
$link = "http://$domain/$targetFile";
echo json_encode(['link'=>$link]);
} else {
echo json_encode(['error'=>'上传失败']);
}
?>

<!DOCTYPE html>
<html>
<head>
<title>图片转链接工具</title>
<style>
.upload-container {
max-width: 500px;
margin: 50px auto;
padding: 20px;
border: 2px dashed #ccc;
text-align: center;
}
#preview {
max-width: 100%;
margin-top: 20px;
display: none;
}
#result {
margin-top: 20px;
word-break: break-all;
}
</style>
</head>
<body>
<div class="upload-container">
<h2>上传图片生成链接</h2>
<input type="file" id="fileInput" accept="image/*">
<button onclick="uploadImage()">上传</button>
<img id="preview">
<div id="result"></div>
</div>

<script>
function uploadImage() {
const fileInput = document.getElementById('fileInput');
const preview = document.getElementById('preview');
const resultDiv = document.getElementById('result');

if(!fileInput.files[0]) {
alert('请选择图片');
return;
}

const formData = new FormData();
formData.append('file', fileInput.files[0]);

preview.src = URL.createObjectURL(fileInput.files[0]);
preview.style.display = 'block';

fetch('upload.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if(data.error) {
resultDiv.innerHTML = `错误: ${data.error}`;
} else {
resultDiv.innerHTML = `图片链接: <a href="${data.link}" target="_blank">${data.link}</a>`;
}
})
.catch(error => {
resultDiv.innerHTML = '上传出错: ' + error;
});
}
</script>
</body>
</html>

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^uploads/(.*)$ /upload.php?file=$1 [L]