n/programu/mlw10086 · 2024-11-25
注册 登录
n/program · 2024-11-25 · 404 次浏览
u/mlw10086白银

大厂图床六间房

原帖https://hostloc.com/thread-1367276-1-1.html
根据原帖修改为php版本
代码index.html

```<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>6间房图片上传</title>
<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.4/weui.min.css">
<style>
body {
background-color: #f1f1f1;
color: #333;
font-family: "Microsoft YaHei", "Hiragino Sans GB", sans-serif;
}
.container {
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
.main-content {
background-color: #fff;
border-radius: 10px;
padding: 30px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
#drop-area {
border: 2px dashed #FFC300;
border-radius: 10px;
padding: 40px;
text-align: center;
margin-bottom: 20px;
transition: all 0.3s ease;
min-height: 200px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#drop-area:hover {
background-color: #FFF9E6;
}
#drop-area.dragover {
background-color: #FFF9E6;
box-shadow: inset 0 0 10px rgba(255,195,0,0.3);
}
.thumb {
width: 80px;
height: 80px;
object-fit: cover;
margin: 5px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.weui-btn {
font-weight: bold;
}
.weui-btn_warn {
background-color: #fff;
color: #FFC300;
border: 1px solid #FFC300;
}
.weui-cell {
background-color: #f9f9f9;
border-radius: 5px;
margin-bottom: 10px;
display: flex;
flex-direction: row;
align-items: center;
}
.weui-cell__bd {
flex: 1;
}
.weui-cell__ft {
margin-left: 10px;
}
.weui-input {
border: none;
background-color: transparent;
padding: 5px 10px;
width: 100%;
box-sizing: border-box;
}
.button-container {
display: flex;
gap: 20px;
}
.button-container .weui-flex__item {
flex: 1;
}
@media (max-width: 480px) {
.container {
padding: 10px;
}
.main-content {
padding: 20px;
}
#drop-area {
padding: 20px;
}
.thumb {
width: 60px;
height: 60px;
}
.weui-cell {
flex-direction: column;
align-items: stretch;
}
.weui-cell__ft {
margin-left: 0;
margin-top: 10px;
}
.weui-btn_mini {
width: 100%;
}
.button-container {
flex-direction: column;
gap: 10px;
}
.button-container .weui-flex__item {
width: 100%;
}
}
.code-tabs {
display: flex;
justify-content: space-around;
margin-bottom: 10px;
}
.code-tab {
padding: 5px 10px;
cursor: pointer;
border-bottom: 2px solid transparent;
}
.code-tab.active {
border-bottom-color: #FFC300;
}
.code-content {
display: none;
}
.code-content.active {
display: block;
}
</style>
</head>
<body>
<div class="container">
<div class="main-content">
<h2 class="weui-panel__hd" style="text-align: center; margin-bottom: 20px;">6间房图片上传</h2>
<div id="drop-area" class="weui-cells weui-cells_form">
<div>
<p>拖放图片到此处或点击选择文件</p>
<p>也可以直接粘贴图片</p>
</div>
<input type="file" id="fileElem" accept="image/*" style="display:none">
<div id="thumb-container"></div>
</div>
<div class="button-container">
<div class="weui-flex__item">
<a href="javascript:" id="upload-btn" class="weui-btn weui-btn_primary">开始上传</a>
</div>
<div class="weui-flex__item">
<a href="javascript:" id="clear-btn" class="weui-btn weui-btn_warn">清除</a>
</div>
</div>
<div id="result-container"></div>
</div>
</div>

&lt;script src="https://res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"&gt;&lt;/script&gt;
&lt;script&gt;
    const dropArea = document.getElementById('drop-area');
    const fileElem = document.getElementById('fileElem');
    const thumbContainer = document.getElementById('thumb-container');
    const resultContainer = document.getElementById('result-container');
    const uploadBtn = document.getElementById('upload-btn');
    const clearBtn = document.getElementById('clear-btn');

    let fileToUpload = null;

    uploadBtn.addEventListener('click', () =&gt; {
        if (!fileToUpload) {
            weui.topTips('请选择文件后再上传', 2000);
            return;
        }
        uploadFile();
    });

    clearBtn.addEventListener('click', () =&gt; {
        thumbContainer.innerHTML = '';
        resultContainer.innerHTML = '';
        fileToUpload = null;
        weui.toast('已清除', 1000);
    });

    dropArea.addEventListener('dragover', (event) =&gt; {
        event.preventDefault();
        dropArea.classList.add('dragover');
    });

    dropArea.addEventListener('dragleave', () =&gt; {
        dropArea.classList.remove('dragover');
    });

    dropArea.addEventListener('drop', (event) =&gt; {
        event.preventDefault();
        dropArea.classList.remove('dragover');
        const file = event.dataTransfer.files[0];
        if (file &amp;&amp; file.type.startsWith('image/')) {
            handleFile(file);
        } else {
            weui.topTips('请上传图片文件', 2000);
        }
    });

    dropArea.addEventListener('click', () =&gt; {
        fileElem.click();
    });

    fileElem.addEventListener('change', () =&gt; {
        if (fileElem.files.length &gt; 0) {
            handleFile(fileElem.files[0]);
        }
    });

    document.addEventListener('paste', (event) =&gt; {
        const items = event.clipboardData.items;
        for (let i = 0; i &lt; items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
                const blob = items[i].getAsFile();
                handleFile(blob);
                break;
            }
        }
    });

    function handleFile(file) {
        fileToUpload = file;
        displayThumbnail(file);
    }

    function displayThumbnail(file) {
        const reader = new FileReader();
        reader.onloadend = () =&gt; {
            thumbContainer.innerHTML = '';
            const img = document.createElement('img');
            img.src = reader.result;
            img.classList.add('thumb');
            thumbContainer.appendChild(img);
        };
        reader.readAsDataURL(file);
    }

    function uploadFile() {
        const formData = new FormData();
        formData.append('file', fileToUpload);
        formData.append('pid', `${1001 + Math.floor(Math.random() * 9)}`);
        formData.append('size', 'c6');
        formData.append('callbackUrl', 'https://v.6.cn/profile/transferStation.html');
        formData.append('callbackFun', `window.parent.${crypto.randomUUID().split('-')[0]}`);

        const loadingTip = weui.loading('上传中...');

        fetch('upload.php', {
            method: 'POST',
            body: formData
        })
        .then(response =&gt; response.json())
        .then(data =&gt; {
            loadingTip.hide();
            if (data.success &amp;&amp; data.url) {
                weui.toast('上传成功', 1000);
                displayResult(data.url, fileToUpload.name);
            } else {
                weui.topTips('上传失败: ' + (data.message || '未知错误'), 2000);
            }
        })
        .catch(error =&gt; {
            loadingTip.hide();
            weui.topTips('上传失败: ' + error.message, 2000);
        });
    }

    function displayResult(imgUrl, fileName) {
        const resultItem = document.createElement('div');
        resultItem.classList.add('weui-cell');

        const cellBody = document.createElement('div');
        cellBody.classList.add('weui-cell__bd');

        const codeTabs = document.createElement('div');
        codeTabs.classList.add('code-tabs');
        ['URL', 'UBB', 'Markdown', 'HTML'].forEach((tabName, index) =&gt; {
            const tab = document.createElement('div');
            tab.classList.add('code-tab');
            tab.textContent = tabName;
            tab.addEventListener('click', () =&gt; switchTab(resultItem, index));
            codeTabs.appendChild(tab);
        });
        cellBody.appendChild(codeTabs);

        const codeContents = [
            imgUrl,
            `[img]${imgUrl}[/img]`,
            `![${fileName}](${imgUrl})`,
            `&lt;img src="${imgUrl}" alt="${fileName}"&gt;`
        ];

        codeContents.forEach((content, index) =&gt; {
            const codeContent = document.createElement('div');
            codeContent.classList.add('code-content');
            const input = document.createElement('input');
            input.type = 'text';
            input.value = content;
            input.readOnly = true;
            input.classList.add('weui-input');
            codeContent.appendChild(input);
            cellBody.appendChild(codeContent);
        });

        const copyButton = document.createElement('a');
        copyButton.classList.add('weui-btn', 'weui-btn_mini', 'weui-btn_primary');
        copyButton.textContent = '复制';
        copyButton.addEventListener('click', () =&gt; {
            const activeInput = resultItem.querySelector('.code-content.active input');
            activeInput.select();
            document.execCommand('copy');
            weui.toast('已复制', 1000);
        });

        const cellFoot = document.createElement('div');
        cellFoot.classList.add('weui-cell__ft');
        cellFoot.appendChild(copyButton);

        resultItem.appendChild(cellBody);
        resultItem.appendChild(cellFoot);
        resultContainer.appendChild(resultItem);

        switchTab(resultItem, 0);
    }

    function switchTab(resultItem, activeIndex) {
        const tabs = resultItem.querySelectorAll('.code-tab');
        const contents = resultItem.querySelectorAll('.code-content');
        
        tabs.forEach((tab, index) =&gt; {
            if (index === activeIndex) {
                tab.classList.add('active');
                contents[index].classList.add('active');
            } else {
                tab.classList.remove('active');
                contents[index].classList.remove('active');
            }
        });
    }
&lt;/script&gt;

</body>
</html>
```

try {
if (!isset($_FILES['file'])) {
throw new Exception('没有接收到文件');
}

$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
    throw new Exception('文件上传错误:' . $file['error']);
}

$url = 'https://pic.v.6.cn/api/uploadForGeneral.php';
$pid = '100' . rand(1, 9);
$callbackUrl = 'https://v.6.cn/profile/transferStation.html';
$callbackFun = 'window.parent.' . substr(uniqid(), 0, 8);

$postData = array(
    'pid' =&gt; $pid,
    'size' =&gt; 'c6',
    'callbackUrl' =&gt; $callbackUrl,
    'callbackFun' =&gt; $callbackFun,
    'file' =&gt; new CURLFile($file['tmp_name'], $file['type'], $file['name'])
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    throw new Exception('CURL错误:' . curl_error($ch));
}

$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);

if (preg_match('/Location:.*json=(.*)/i', $headers, $matches)) {
    $uploadResult = json_decode($matches[1], true);
    
    if ($uploadResult['flag'] === '001') {
        echo json_encode([
            'success' =&gt; true,
            'url' =&gt; $uploadResult['content']['url']['link']
        ]);
    } else {
        throw new Exception('上传服务器返回错误');
    }
} else {
    throw new Exception('未找到上传结果');
}

curl_close($ch);

} catch (Exception $e) {
echo json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}

```
测试图片~~

0
9
登录后参与讨论。
u/udc2b6nr 广告
QuicksilverVPN

快银 VPN,一键连接全球节点,线路稳定、延迟低。支持 Windows、macOS 等多平台,TUN 全局模式覆盖全部应用流量。无需复杂配置,下载即用。

umami.dnsl.top 了解更多

9 条回复

排序
  1. James 💯 传奇 MANAGER 2024-11-25

    [[2],[2,40]]

    0
  2. James 💯 传奇 MANAGER 2024-11-25

    挺快,感谢分享。不知道有没有上传限制,能不能传视频。

    0
  3. kefeng 黄金 2024-11-25

    感谢分享

    0
  4. mlw10086 白银 楼主 2024-11-25

    @"James"#p164753 视频的话,最近在研究另一个大厂的接口了。

    0
  5. china97 白银 2024-11-25

    图片速度还挺快,不愧是老品牌

    0
  6. lilingfeng 白银 2024-11-25

    [code]
    import json
    import urllib.parse

    import requests
    import uuid
    import random
    files = {
    'file': open("wudi.jpg", 'rb'),
    }
    form = {
    'pid': str(1001 + random.randint(0, 8)),
    'size': 'c6',
    'callbackUrl': 'https://v.6.cn/profile/transferStation.html',
    'callbackFun': f"window.parent.{str(uuid.uuid4()).split('-')[0]}"
    }

    upload = requests.post(
    'https://pic.v.6.cn/api/uploadForGeneral.php',
    files=files,
    data=form,
    timeout=10
    )
    data=urllib.parse.unquote(urllib.parse.urlparse(upload.url).query.split('&')[2]).removeprefix("json=")

    upload = json.loads(data)

    if upload['flag'] != '001':
    raise Exception

    print(upload['content']['url']['link'])

    [/code]

    全国 14ms 也是无敌

    0
  7. mili 荣誉会员 王者 圣贤 2024-11-25

    感谢分享 坐等上传文件或者视频的成品 😎

    0
  8. wangyou 白银 2024-11-25

    大佬666,厉害

    0
  9. NodeLoc 官方 2024-11-26

    @"菜鸡鲲"#p164703 謝分享!收藏了。

    0