前端文件
<!DOCTYPE html>
<html>
<head><title>文件上傳</title>
</head>
<body>
<h1>文件上傳1-相對慢,需要等待本地選擇的文件全部上傳完成后,服務器再保存</h1>
<form id="uploadFormBatch" enctype="multipart/form-data"><input type="file" id="fileInputBatch" name="file" multiple><br><br><input type="button" id="btnBatch" value="批量提交整體上傳" onclick="clearLog(); uploadFilesBatch()">
</form><h1>文件上傳2-相對快-推薦使用,本地上傳一個,服務器保存一個,前端循環</h1>
<form id="uploadFormOne" enctype="multipart/form-data"><input type="file" id="fileInputOne" name="file" multiple><br><br><input type="button" id="btnOne" value="批量提交循環上傳" onclick="clearLog(); uploadFilesOne()">
</form>
<div id="log"></div>
<script>const url = 'http://localhost:8421'function clearLog() {const logDiv = document.getElementById('log');logDiv.innerHTML = ""; // 清空日志內容}// 獲取當前時間function getDate() {var now = new Date();console.log("當前時間是:" + now);return now;}// 獲取兩個時間的差值function diffDate(startTime, endTime) {// 獲取兩個時間的時間戳var startTimeStamp = startTime.getTime();var endTimeStamp = endTime.getTime();// 計算時間差(毫秒)var differenceInMilliseconds = endTimeStamp - startTimeStamp;// 將毫秒轉換為秒var differenceInSeconds = differenceInMilliseconds / 1000;console.log("兩個時間的差是:" + differenceInSeconds + "秒");return differenceInSeconds;}// 時間格式化 yyyy-MM-dd HH:mm:ssfunction formatDate(date) {const pad = (num) => (num < 10 ? '0' + num : num);var year = date.getFullYear();var month = pad(date.getMonth() + 1);var day = pad(date.getDate());var hour = pad(date.getHours());var minute = pad(date.getMinutes());var second = pad(date.getSeconds());return `${year}-${month}-${day} ${hour}:${minute}:${second}`;}function uploadFilesBatch() {const files = document.getElementById('fileInputBatch').files;const butBatch = document.getElementById('btnBatch');butBatch.disabled = true;// 禁用按鈕const startDate = getDate();appendLog('程序啟動-準備開始上傳:' + formatDate(startDate));const formData = new FormData();for (let i = 0; i < files.length; i++) {formData.append('files', files[i]);}fetch(url + '/upload_batch', {method: 'POST',body: formData}).then(response => {return response.text();}).then(data => {if (data === '文件上傳成功!') {// console.log(`文件 ${files.length} 上傳成功`);butBatch.disabled = false; //解除禁用const endDate = getDate();appendLog(`文件 ${files.length} 上傳成功:` + formatDate(endDate));appendLog(`總共耗時:` + diffDate(startDate, endDate) + `秒`);} else {console.error(`文件 ${files.length} 上傳失敗`);appendLog(`文件 ${files.length} 上傳失敗`);}}).catch(error => {console.error(`文件 ${files.length} 上傳失敗: ${error}`);appendLog(`文件 ${files.length} 上傳失敗: ${error}`);});}function uploadFilesOne() {const files = document.getElementById('fileInputOne').files;const btnOne = document.getElementById('btnOne');btnOne.disabled = true; // 禁用按鈕let index = 0;const startDate = getDate();appendLog('程序啟動-準備開始上傳:' + formatDate(startDate));function uploadFile(index) {const startDateOne = getDate();if (index >= files.length) {const endDate = getDate();appendLog("所有文件處理完成:" + formatDate(endDate));appendLog(`總共耗時:` + diffDate(startDate, endDate) + `秒`);btnOne.disabled = false;// 全部上傳完成,解除禁用return;}const file = files[index];const formData = new FormData();formData.append('file', file);appendLog(`文件 ${file.name} 正在上傳··· ···`)fetch(url + '/upload_one', {method: 'POST',body: formData}).then(response => {return response.text();}).then(data => {if (data === '文件上傳成功!') {const endDateOne = getDate();appendLog(`文件 ${file.name} 上傳成功,耗時:` + diffDate(startDateOne, endDateOne) + `秒`);uploadFile(index + 1); // 遞歸調用上傳下一個文件} else {appendLog(`文件 ${file.name} 上傳失敗:${data}`);uploadFile(index); // 文件上傳失敗則繼續上傳}}).catch(error => {console.error(`文件 ${file.name} 上傳失敗: ${error}`);appendLog(`文件 ${file.name} 上傳失敗: ${error}`);});}uploadFile(index);}function appendLog(message) {const logDiv = document.getElementById('log');// logDiv.innerHTML += message + "<br>";logDiv.innerHTML = `<p>${message}</p>` + logDiv.innerHTML;}
</script>
</body>
</html>
后端文件使用python
# -*- ecoding: utf-8 -*-
# @ModuleName: test002
# 當你要使用這份文件時,
# 代表你已經完全理解文件內容的含義,
# 并愿意為使用此文件產生的一切后果,付全部責任
# @Funcation:
# @Author: darling
# @Time: 2024-06-17 14:21
from flask_cors import CORS
from flask import Flask, request
import os
from loguru import loggerapp = Flask(__name__)
CORS(app)@app.route('/upload_one', methods=['POST'])
def upload_one():'''前端上傳,批量選擇后,前端循環上傳,后端單個接收:return:'''file = request.files['file'] # 獲取上傳的文件if file:logger.info('獲取到文件{}', file.filename)file.save(os.path.join('files', file.filename)) # 保存文件到當前目錄logger.info('保存結束{}', file.filename)return '文件上傳成功!'else:return '文件上傳失敗!'@app.route('/upload_batch', methods=['POST'])
def upload_batch():'''前端上傳,批量選擇后一次性上傳,后端循環保存:return:'''files = request.files.getlist('files') # 獲取上傳的文件列表if files:for file in files:logger.info('獲取到文件{}', file.filename)file.save(os.path.join('files', file.filename)) # 保存文件到當前目錄logger.info('保存結束{}', file.filename)return '文件上傳成功!'else:return '文件上傳失敗!'if __name__ == '__main__':app.run(host='0.0.0.0', port=8421)