目錄
Toggle簡介
本教學將詳細介紹如何在網站中自行上傳PDF文件。透過本文,你將學會如何準備文件、建立上傳功能,以及處理上傳的文件。
準備工作
在開始之前,請確保你的開發環境中已安裝必要的工具和庫,例如HTML、CSS和JavaScript。如果你打算使用伺服器端語言,如PHP或Node.js,請確保你的伺服器配置已完成。
建立專案結構
首先,建立一個新專案資料夾,並在其中創建以下子資料夾和文件:
index.html
– 主要HTML文件style.css
– 網站樣式文件script.js
– JavaScript文件uploads/
– 用於存儲上傳的PDF文件的資料夾
建立HTML表單
在index.html
文件中,添加一個表單,讓用戶可以選擇並上傳PDF文件。
<form id="uploadForm" enctype="multipart/form-data">
<label for="pdfFile">選擇PDF文件:</label>
<input type="file" id="pdfFile" accept="application/pdf">
<button type="submit">上傳</button>
</form>
前端處理
接下來,我們在script.js
文件中添加JavaScript代碼,以處理表單的提交及文件上傳。
document.getElementById('uploadForm').addEventListener('submit', function(event) {
event.preventDefault();
const fileInput = document.getElementById('pdfFile');
const file = fileInput.files[0];
if (!file) {
alert('請選擇一個PDF文件');
return;
}
const formData = new FormData();
formData.append('pdf', file);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(response => response.text())
.then(data => {
alert('文件上傳成功');
})
.catch(error => {
console.error('上傳失敗:', error);
alert('文件上傳失敗');
});
});
伺服器端處理
在伺服器端,我們需要編寫代碼來接收和儲存上傳的PDF文件。以下以Node.js和Express為例。
安裝所需模組
首先,安裝必要的Node.js模組:
npm install express multer
建立伺服器代碼
創建一個server.js
文件,並添加以下代碼:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.use(express.static(path.join(__dirname, 'public')));
app.post('/upload', upload.single('pdf'), (req, res) => {
if (!req.file) {
return res.status(400).send('沒有上傳文件');
}
res.send('文件上傳成功');
});
app.listen(3000, () => {
console.log('伺服器運行在 http://localhost:3000');
});
測試上傳功能
啟動你的伺服器,並在瀏覽器中打開http://localhost:3000
。使用上傳表單選擇一個PDF文件並進行上傳,確認文件已成功上傳至伺服器的uploads/
資料夾。
結語
恭喜你!你已經成功建立了一個簡單的PDF文件上傳功能。你可以根據具體需求進一步擴展和優化此功能,例如增加文件格式檢查、文件大小限制,以及文件下載功能。