您的位置:首页 > 财经 > 产业 > 简易跨平台上传文件,前后端demo

简易跨平台上传文件,前后端demo

2024/12/22 0:16:50 来源:https://blog.csdn.net/brightgreat/article/details/140057413  浏览:    关键词:简易跨平台上传文件,前后端demo

前端文件

<!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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com