1. 程式人生 > >Ajax+Python flask實現上傳文件功能

Ajax+Python flask實現上傳文件功能

pad info import code %s 選擇 path ont 功能

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

Ajax+Python flask實現上傳文件功能