python-flask-上传多个文件并存储

本地环境:win10 / centos6 , python3


flask入门看这里:

↓

python-flask结合bootstrap实现网页小工具实例-半小时速通版_bootstrap flask-CSDN博客

https://blog.csdn.net/pxy7896/article/details/137854455

动态添加和删除表格中的行,看这里:

↓

javascript-动态增加和删除表格的行-CSDN博客

https://blog.csdn.net/pxy7896/article/details/141030235


问题描述

在前台上传1~N个文件,后台接收并存储。

实现效果

点击"添加峰图"按钮,可以不断加行:

实际的html内容类似:

后台则需要接收这些附件(前一个input也要)。

解决方案

在前台构建一个form,在里面放一个table,然后在列中增加文件上传按钮,如下所示:

html 复制代码
<form action="run_command_ab1" id="main_form" >
	<div id="suborderlist" class="row col-md-12">
		<table>
			<!-- 略去一些内容 -->
			<!-- 这是编号 -->
			<td name="rowIdx" style="width:10%;"></td>
			<td style="width:40%;">
				<input name="attach" type="file" id="customFile">
            </td>
		</table>
</form>

提交按钮的id是submitButton,加上点击操作:

javascript 复制代码
$("#submitButton").click(function () {
	// 构造数据
	var formData = new FormData();
	var attachList = document.getElementsByName("rowIdx");
    for (var x=0; x<attachList.length; x++) {
    	// 接收前面input的细节,略
		// 拼接一下文件的id
		var idx = "attach." + attachList[x].innerText.toString();
    	var attachFile = document.getElementById(idx).files[0];
    	if (attachFile == null) {
			// 处理空文件
    		var blob = new Blob([], {type: "text/plain;charset=utf-8"});
    		formData.append("subAttach", blob);
    	} else {
    		formData.append("subAttach", attachFile);
    	}
    }
    // 剩余数据
    // 这里main_form是当前整个form的id
	formData.append("ab1Order", $("#main_form").serialize());
    $.ajax({
        type: 'POST',
        url: "/run_command_ab1",
        data: formData,
		processData: false, // jQuery不要处理发送的数据
        contentType: false, // jQuery不要设置Content-Type请求头
        success: function (resp) {
			// 做一些处理
		}
    });
});

在后台这样写:

python 复制代码
@app.route('/run_command_ab1', methods=['POST'])
def run_command_ab1():
    if request.method == 'POST':
        #print(request.form) 
        # ImmutableMultiDict([('ab1Order', 'sampleId=test&target=313&target=21&target=')])
        # 所以这样提取信息
        info = request.form['ab1Order']
        
        #print(request.files)
        # ImmutableMultiDict([('subAttach', <FileStorage: 'xxx.ab1' ('application/octet-stream')>)])
        # 这样获取文件列表
        files = request.files.getlist('subAttach')
        # 遍历
        for f in files:
            f.save("/this/is/the/path/" + f.filename)
        return '文件已上传成功!'

END.

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github