目录

  • 前言
    • JS
    • Form的enctype属性
    • Input
    • MIME类型(更多直接百度,类型超乎你的想想)
  • 上传单个文件
    • html代码部分
    • javascript代码部分
    • flask 视图函数部分
  • 上传多个文件
    • html
    • js
    • 出问题解决方案

前言

JS

为什么要用ajax来提交
在使用from提交时,浏览器会向服务器发送选中的文件的内容而不仅仅是发送文件名。

为安全起见,即file-upload 元素不允许 HTML 作者或 JavaScript 程序员指定一个默认的文件名。HTML value 属性被忽略,并且对于此类元素来说,value属性是只读的,这意味着只有用户可以输入一个文件名。当用户选择或编辑一个文件名时,file-upload 元素触发 onchange 事件句柄。

利用form提交会导致页面刷新,体验不好,所以使用AJAX进行文件上传是个不错的选择。但这需要我们自己来组织通过POST请求发送的内容
FormData对象

通过FormData对象可以组装一组用 XMLHttpRequest发送请求的键/值对。它可以更灵活方便的发送表单数据,因为可以独立于表单使用。如果你把表单的编码类型设置为multipart/form-data ,则通过FormData传输的数据格式和表单通过submit() 方法传输的数据格式相同。 —— MDN web docs

Form的enctype属性

enctype这个属性管理的是表单的MIME编码,它一共有三个属性:

描述
application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码,用来制定传输数据的特殊类型,如mp3、jpg
text/plain 纯文本传输

Input

value 保存了用户指定的文件的名称
type=“file” 设置input类型为file
multiple=“multiple” 可多选,不设置为单选
accept=“…” 设置可选文件的MIME_type。在设置之后点击选择文件按钮会默认显示符合设置的MIME_type的文件(存在兼容性)。具体的文件类型对应的MIME类型可以搜索到,这里列出我用到的类型:

MIME类型(更多直接百度,类型超乎你的想想)

文件类型 MIME类型
.txt text/plain
.pdf application/pdf
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls application/vnd.ms-excel
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation

上传单个文件

html代码部分

<form   id="uploadForm"  method="post" enctype="multipart/form-data"><label  >上传电子书</label><input type="file"  name="file" ><button  id="upload" type="button"  name="button" >上传</button></br></br></br>
</form>

javascript代码部分

<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script>
<script>$("#upload").click(function(){var formData = new FormData($('#uploadForm')[0]);$.ajax({type: 'post',url: "{{ url_for('.regression_report') }}", //上传文件的请求路径必须是绝对路劲data: formData,cache: false,processData: false,contentType: false,success:function(data){// 这里是访问成功时被自动执行的代码// 拆分返回值信息(具体返回什么东西就看视图函数中定义的json格式)status_ret = data.status;errmsg_ret = data.errmsg;layer.msg(errmsg_ret);switch (status_ret){case 0:setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");breakdefault:setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");break}},error:function(jqXHR){// 这里是访问失败时被自动调用的代码}});
});
</script>

当你的页面样式比较多的时候,可能上述方法无法传入文件,下面这种方法比较强,推荐看看

<form class="info" method="post" enctype="multipart/form-data"><div class="form-group"><label>File upload</label><input id="id_regression_html" type="file" name="regression_html" class="file-upload-default"><div class="input-group col-xs-12"><input type="text" class="form-control file-upload-info" disabled="" placeholder="Upload Regression.html"><span class="input-group-append"><button id="html_upload" class="file-upload-browse btn btn-gradient-primary" type="button">Html Upload</button></span></div></div><button id="id_ajax_submit" type="button" class="btn btn-gradient-primary mr-2">Submit</button>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script>
<script>$("#id_ajax_submit").click(function(){// var formData = new FormData($('#uploadForm')[0]);let formData = new FormData();let my_file = document.getElementById('id_regression_html');// @Param: <input name="regression_html">// @Param: myFile.file[0]为第一个文件(单选),多个文件(多选)则要循环添加formData.append('regression_html',my_file.files[0]);$.ajax({type: 'post',url: "{{ url_for('.regression_report') }}", //上传文件的请求路径必须是绝对路劲data: formData,cache: false,async: false,processData: false, //告诉jquery不要处理发送的数据contentType: false, //告诉jquery不要设置content-Type请求头success:function(data){// 这里是访问成功时被自动执行的代码// 拆分返回值信息(具体返回什么东西就看视图函数中定义的json格式)status_ret = data.status;errmsg_ret = data.errmsg;layer.msg(errmsg_ret);switch (status_ret){case 0:setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");breakcase 1:setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");breakdefault:setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");break}},error:function(jqXHR){// 这里是访问失败时被自动调用的代码}});});
</script>

flask 视图函数部分

@admin_blu.route("/toolReg", methods=['GET', 'POST'])
def regression_report():if request.method == "GET":return render_template('index.html')elif request.method == "POST":# TODO: 获取设置# TODO: 获取文件f = request.files.get('file')if f and f.filename.__contains__('.html'):upload_path = os.path.join(current_app.root_path, 'static/upload/html', f.filename)            download_path = os.path.join(current_app.root_path, 'static/upload/html', 'xlsx')# TODO: 类实例化,同步执行f.save(upload_path)ret = {"status": 0,"errmsg": "上传成功"}return jsonify(ret)return redirect(url_for(".index.html"))

上传多个文件

html

<form id="uploadForm" enctype="multipart/form-data"><input type="file" name="file" multiple="multiple" />
</form>
<button id="btnUpload">上传文件</button>

js

<script>$("#btnUpload").on("click", function(){var formdata = new FormData($("#uploadForm")[0]);alert(formdata);$.ajax({type: "post",url: "/Attendance/UploadFile2/",//url地址contentType: false,cache: false,processData: false,data: formdata,success: function (data) {console.log(data);}});
});
</script>

出问题解决方案

//将formdata改用下面的方式试下
var formdata = new FormData();
var files = $("input[type='file']")[0].files;
for (var i = 0; i < files.length; i++) {formdata.append("file", files[i]);
}

Python flask使用ajax上传文件相关推荐

  1. flask ajax 上传 图片,flask jQuery ajax 上传文件

    1.html 代码 注:1.html 部分主要是一个form表单,其中表单的enctype = "multipart/form-data" 必须要有. 2.由于我的页面背景颜色设置 ...

  2. ajax上传 java,javaWeb中使用ajax上传文件

    javaWeb上传图片 上传文件所必要的两个jar包:commons-fileupload.jar.commons-io.jar. 核心代码: String withPath = req.getSer ...

  3. 上传html 0字节,HTML ajax 上传文件限制文件的类型和文件大小

    html js function getFileType(filePath){ //获取文件的后缀名 var startIndex = filePath.lastIndexOf(".&quo ...

  4. 页面无刷新ajax上传文件--模拟iframe,超简单

    前段时间在解决ajax上传文件时折腾了好一阵.直接用$.post上传文本信息肯定是没有问题的.但是$.post直接上传图片是不可行的. 后来看到网上的一些解决方案,有现成的ajax上传文件的封装的方法 ...

  5. ajax上传文件 获取失败,Ajax上传文件/照片时报错TypeError :Illegal invocation的解决方法...

    本篇文章给大家带来的内容是关于Ajax上传文件/照片时报错TypeError :Illegal invocation的解决方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 问题 A ...

  6. php 通过ajax上传文件,php – 通过ajax上传文件

    我使用2个文件index.js,upload.php尝试通过ajax上传文件(img),如果成功附加到div uploadfile_show. 但它不起作用,几乎没有问题,下面是我的代码有什么建议吗? ...

  7. Django框架 之 Form表单和Ajax上传文件

    Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...

  8. php+ajax上传文件

    直接上源代码 html页面 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > ...

  9. Ajax上传文件的cache、processdata、contentType属性以及FormData对象的总结

    Ajax上传文件的cache.processdata.contentType属性以及FormData对象的总结 前言:在之前的Ajax一次性上传多张图片并实现预览的博客中提到,如果要用 Ajax 上传 ...

最新文章

  1. MySQL 性能优化,索引和查询优化
  2. JavaScript正则表达式快速判断技巧
  3. opencv补全边缘_为什么OpenCV中绘制的轮廓不能填充图像边缘的轮廓?
  4. iOS私有属性的访问与修改
  5. sklearn快速入门教程:(二)线性回归
  6. python映射类型包括哪三种_python新手入门必备——映射类型相关函数
  7. 区位码\机器码\内码关系
  8. 子窗体列表在菜单中的实现
  9. 【转】HMAC哈希消息认证码及算法原理
  10. 使用data()方法缓存数据
  11. 性能优化工作笔记001---springcloud项目性能优化_工作经验随时更新
  12. Linux内核学习笔记(2)-- 父进程和子进程及它们的访问方法
  13. Windows Server 2003 安装教程——图文小白版(附下载地址)
  14. STM32串口通信详解
  15. java毕业设计小区停车场管理系统(附源码、数据库)
  16. 运行vba代码的快捷键
  17. matlab的求解方程组函数solve、dsolve、ode系列
  18. linux中怎么生成hwaddr,linux 下 hwaddr 和 macaddr的区别
  19. c语言水王争霸链表,水王争霸(water)
  20. 成人c语言培训,C语言程序设计在成人教育中教学.doc

热门文章

  1. Linux查看磁盘空间大小的命令
  2. 反编译C语言程序学习笔记
  3. C#面向对象的三大特征
  4. 2021/10/04 北京 鲁班大师技能总结
  5. PAT 一章 字符串 16-20 自用
  6. 黑马点评-优惠券秒杀
  7. Web 2.0时代必读的24本经典书籍
  8. python regularExpression
  9. 硬盘有坏块的数据恢复方法
  10. 网络攻击是如何运作的—一份完整的列表