3

基于Flask开发网站 -- 前端Ajax异步上传文件到后台

 2 years ago
source link: https://my.oschina.net/u/4638454/blog/5157586
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大家好,我是辰哥~

辰哥最近利用空闲时间在写一个在线可视化平台,过程中也觉得一些技术还是比较有意思的,所以就以模块化的形式分享出来。如:从网页界面(前端)上传文件到服务器(后端)。

放一下该模块的界面图瞧一瞧:

点击上传excel文件按钮,选择excel文件后可以在线预览,并且后端接收保存到服务器,本文主要是分享上传文件这块内容。

背景:前端是html,后端使用Flask框架,在前端点击上传一个excel文件,后端接收并保存到本地。

01 前端处理

1.文件选择框

相信写过html代码的都知道,上传文件控件最简单的是html默认的(非使用插件的情况)

<input id="file" name="loadfile" type="file">

文件选择框的id是file,类型是file,通过id去调用js异步代码,类型是指定input是选择本地文件。

这样就定义好一个文件选择框。

2.Ajax异步处理

在使用Ajax异步之前,需要引入Jquery文件

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>

异步代码:

$('#file').change(function (e) {
     var files = e.target.files;
     var formFile = new FormData();
     formFile.append("file", files[0]); //加入文件对象
      $.ajax({
         url: "/upload_file",
         data: formFile,
         type: "post",
         dataType: "json",
         cache: false,//上传文件无需缓存
         processData: false,//用于对data参数进行序列化处理 这里必须false
         contentType: false, //必须
         success: function (result) {
             alert("上传完成!");
         },
     })
});

点击网页的上传excel文件按钮,选择好excel文件之后,自动触发上述的js代码(通过id:file去触发指定js代码)

> 简单介绍: > > (1)e.target.files:选择上传的文件 > > (2)FormData:将上传文件封装到FormData中 > > (3)/upload_file:后端上传的接口(接收文件的入口)

这段js代码的作用就是将选择好的excel文件,上传到后端接口:/upload_file,后端处理完毕之后返回响应值:result,网页提示:上传完成。

02 后端处理

后端使用Python去编写,用的是Flask框架,如果还不明白的flask的简单使用的,可以参考辰哥之前的一篇文章:Flask结合ECharts实现在线可视化效果,超级详细!

这里辰哥直接带大家看后端接口,详细的完整源码,辰哥会在文末直接给出。

# 上传文件
@app.route('/upload_file', methods=['POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        print(f.filename)
        #######################################
        # 毫秒级时间戳
        file_name = str(round(time.time() * 1000))
        dir = str(time.strftime('%y%m%d', time.localtime()))
        upload_path = os.path.join(basepath, 'uploads/'+dir)
        # 判断文件夹是否存在
        if not os.path.exists(upload_path):
            os.mkdir(upload_path)
        #######################################
        file_path = str(file_name)+str(f.filename)
        f.save(upload_path+"/"+file_path)
    return Response(json.dumps(file_path), mimetype='application/json')

简单说明:

(1)接口名称是:/upload_file,接受的请求方式是:post;

(2)request.files['file']:接收上传的文件;

(3)6~16行:在upload文件夹下自动创建以当天日期命名的文件夹,作为保存上传文件的存储路径;

(4)file_name:是当前毫秒级时间戳,对上传的文件重命名:时间戳+原文件名;

(5)Response返回文件路径到前端异步处理函数success:file_path;

前端和后端都处理完毕后,开始调试程序。看看具体效果。

以上就是前端Ajax异步上传文件到后端的内容。

> 完整的源码地址: > > https://wwi.lanzoui.com/imM6bs2f44d

最后说一声:原创不易,求给个赞!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK