jquery ajax 文檔 告訴你能夠使用默認的 application/x-www-form-urlencoded, multipart/form-data, or text/plain
這三種,其它的也能夠,可是須要告訴ajax 的怎樣序列化它。——這句話來源於:https://www.cnblogs.com/htoooth/p/7242217.htmljavascript
app.pyhtml
import os from flask import Flask, request, jsonify, render_template from werkzeug import secure_filename UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/') def index(): return render_template('index.html') @app.route('/uploadfile', methods=['POST']) def upload_file(): if request.method == 'POST': print('request.files', dir(request.files)) file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) url = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(url) return jsonify(dict(url=url,)), 201 if __name__ == "__main__": app.run(debug=True)
index.htmljava
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Flask上傳圖片演示三</title> </head> <body> <h1>Flask上傳本地圖片示例三</h1> <p>不使用表單Form,原生javascript實現ajax,返回上傳的圖片所保存的位置</p> <input type="file" name="file" /> <br> <input type="button" value="上傳" /> <p id="res"></p> <script> var file = document.querySelector('input[type="file"]'); var btn = document.querySelector('input[type="button"]'); //ajax btn.addEventListener('click', function(event){ event.preventDefault(); var data = new FormData(); data.append(file.name, file.files[0]);var xhr = new XMLHttpRequest(); xhr.open('POST', '/uploadfile', true); //xhr.setRequestHeader("Content-Type", "multipart\/form-data;"); //千萬不能要這一句,不然後臺request.files讀不到file xhr.send(data); xhr.addEventListener('loadend', function(){ if(xhr.status == 201){ var res_json = JSON.parse(xhr.responseText); document.querySelector('#res').innerHTML = "上傳的圖片保存在:" + res_json.url; } }, false); }, false); </script> </body> </html>
app.pyjquery
import os from flask import Flask, request, jsonify, render_template from werkzeug import secure_filename UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/') def index(): return render_template('index.html') @app.route('/uploadfile', methods=['POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) url = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(url) return jsonify(dict(url=url,)), 201 if __name__ == "__main__": app.run(debug=True)
index.htmlajax
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Flask上傳圖片演示二</title> </head> <body> <h1>Flask上傳本地圖片示例二</h1> <p>使用表單Form,原生javascript實現ajax,返回上傳的圖片所保存的位置</p> <!-- <form enctype='multipart/form-data'> 注意:非必須指定enctype='multipart/form-data' --> <form> <input type="file" name="file"/> <br> <input type="submit" value="上傳"/> </form> <p id="res"></p> <script> var form = document.querySelector('form'); //ajax form.addEventListener('submit', function(event){ event.preventDefault(); var xhr = new XMLHttpRequest(); xhr.open('POST', '/uploadfile', true); xhr.send(new FormData(form)); //注意:不須要設置Content-Type xhr.addEventListener('loadend', function() { if(xhr.status == 201){ var res_json = JSON.parse(xhr.responseText); document.querySelector('#res').innerHTML = "上傳的圖片保存在:" + res_json.url; } }, false); }, false); </script> </body> </html>
app.pyjson
import os from flask import Flask, request, redirect, url_for, render_template from werkzeug import secure_filename UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/') def index(): return render_template('index.html') @app.route('/uploadfile', methods=['POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) from flask import send_from_directory @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == "__main__": app.run(debug=True)
index.htmlflask
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Flask上傳圖片演示一</title> </head> <body> <h1>Flask上傳本地圖片示例一</h1> <p>使用表單Form,無javascript,跳轉顯示上傳的圖片</p> <form action="/uploadfile" enctype='multipart/form-data' method='POST'> <!-- 注意:三個全指定action, enctype, method --> <input type="file" name="file" style="margin-top:20px;"/> <br> <input type="submit" value="上傳" style="margin-top:15px;"/> </form> </body> </html>
4、預覽、無Form、原生ajaxapi
index.htmlapp
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Flask上傳圖片演示四</title> </head> <body> <h1>Flask上傳本地圖片示例四</h1> <p>上傳前預覽圖片,不使用表單Form,原生ajax,返回上傳的圖片所保存的位置</p> <img id="base64image" src="" style="max-height:150px;"/> <br /> <input type="file" name="image" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"/> <br /> <input type="button" value="上傳"/> <p id="res"></p> <script> var base64image = document.querySelector('#base64image'); var fileElement = document.querySelector('input[type="file"]'); var btnElement = document.querySelector('input[type="button"]'); //預覽 fileElement.addEventListener('change', function(event){ if (!event.target.files || !event.target.files[0]) { return; } var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); reader.addEventListener("load", function(e){ base64image.src = e.target.result; //base64編碼 }, false); },false); //ajax btnElement.addEventListener('click', function(event){ event.preventDefault(); var data = new FormData(); data.append(fileElement.name, fileElement.files[0]); //添加圖片信息 var xhr = new XMLHttpRequest(); xhr.open("post", "/uploadfile", true);//true即異步 //xhr.setRequestHeader('Content-Type', 'multipart/form-data'); //千萬別寫這句!! xhr.send(data); xhr.addEventListener("loadend", function(event){ if(xhr.status == 201){ // 201,去看app.py!! var res = JSON.parse(xhr.responseText); //接收的是json數據 console.log(res); } }, false); },false); </script> </body> </html>