Ajax+Python flask实现上传文件功能

HTML:

<div  >
       <input type="file" name="FileUpload" id="FileUpload">
       <a class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</a>
</div>

Ajax实现:

<script type="text/jscript">
 
       $(function () {
           $("#btn_uploadimg").click(function () {
               var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
               if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                   alert("请选择图片");
                   return;
               }
               var formFile = new FormData();
               formFile.append("action", "UploadVMKImagePath");  
               formFile.append("file", fileObj); //加入文件对象
 
               //第一种  XMLHttpRequest 对象
               //var xhr = new XMLHttpRequest();
               //xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
               //xhr.onload = function () {
               //    alert("上传完成!");
               //};
               //xhr.send(formFile);
 
               //第二种 ajax 提交
 
               var data = formFile;
               $.ajax({
                   url: "/upload/",
                   data: data,
                   type: "Post",
                   dataType: "json",
                   cache: false,//上传文件无需缓存
                   processData: false,//用于对data参数进行序列化处理 这里必须false
                   contentType: false, //必须
                   success: function (result) {
                       alert("上传完成!");
                   },
               })
           })
       })
 
   </script>

后台flask:

from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os
from flask import send_from_directory
from werkzeug import SharedDataMiddleware

UPLOAD_FOLDER = '/uploads'  #文件存放路径
ALLOWED_EXTENSIONS = set(['jpg']) #限制上传文件格式

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return  '{"filename":"%s"}' % filename
    return ''

以上基本上就可以实现上传功能了。

以下是对界面样式,就是选择文件的那个上传按钮样式做了一些修改

如下图:

HTML:此处还添加了文件格式限制,只能选择 .torrent 文件

<div class="divcenter" style="width:1025px">
            <div style="width:100%;height:600px">
                <div id="div_torrent" style="overflow:hidden">
                    <a id="btn_file" href="javascript:;" class="file" style="margin-top:5px;margin-bottom:5px;float:left;">选择文件
                       <input type="file" name="FileUpload" id="FileUpload" accept=".torrent">
                    </a>
                    <div id="showFileName" style="float:left;margin-top:7px;margin-bottom:5px;"></div>
                    <input id="btn_upload" type="button" value="上传" onclick="onsubmit" class="file" style="float:right;width:65px; height: 33px;left: 4px;background-color:rgba(255, 206, 68, 0.6);cursor:hand;margin-top:5px;margin-bottom:5px;margin-right:5px;border-color:red" />
                </div>
            </div>
    </div>

CSS样式:

.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}

 以上代码选择文件后,不会显示文件名,所以需要添加一个事件:

<script type="text/jscript">
       $(function () {
                $("#btn_file").on("change","input[type='file']",function(){
                    var filePath=$(this).val();
                    if(filePath.indexOf("torrent")!=-1){
                        var arr=filePath.split('\\');
                        var fileName=arr[arr.length-1];
                        $("#showFileName").html(fileName);

                    }else{
                        $("#showFileName").html("");
                        }
                   })
                })
    </script>

上传的代码没做修改:此处增加了一个最大文件大小限制 5Mb

<script type="text/jscript">

       $(function () {
           $("#btn_upload").click(function () {
               var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
               if (typeof (fileObj) == "undefined" || fileObj.size <= 0|| $("#showFileName").html()=="") {
                   alert("请选择BT种子");
                   return;
               }if(fileObj.size>5242880)
               {
                    alert("BT种子限制最大 5Mb");
                    return;
               }
               var formFile = new FormData();
               formFile.append("action", "UploadTorrentPath");
               formFile.append("file", fileObj); //加入文件对象

               //第一种  XMLHttpRequest 对象
               //var xhr = new XMLHttpRequest();
               //xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
               //xhr.onload = function () {
               //    alert("上传完成!");
               //};
               //xhr.send(formFile);

               //第二种 ajax 提交

               var data = formFile;
               $.ajax({
                   url: "/upload/",
                   data: data,
                   type: "Post",
                   dataType: "json",
                   cache: false,//上传文件无需缓存
                   processData: false,//用于对data参数进行序列化处理 这里必须false
                   contentType: false, //必须
                   success: function (result) {
                       alert("上传完成!");
                   },
                    error: function (xmlrequest, textStatus, errorThrown) {
                        alert("上传失败!");
                    //alert("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));
                    console.log("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));
                }
               })
           })
       })

   </script>

 PS.喜欢看动漫的同学,可以来我的网站下载动漫哦  www.wikibt.com

参考文章1:https://www.cnblogs.com/LoveTX/p/7081515.html

参考文章2:https://www.haorooms.com/post/css_input_uploadmh

 

posted on 2019-01-20 16:16  梦琪小生  阅读(7799)  评论(2编辑  收藏  举报

导航