文件上传flask按照后端官网示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| from flask import Flask, request, jsonify import flask_cors
from werkzeug.utils import secure_filename app = Flask(__name__)
flask_cors.CORS(app) @app.route("/uploadfile", methods=['post']) def upload_file(): try: f = request.files.get("pic") f.save('./static/' + secure_filename(f.filename)) place = './static/' + secure_filename(f.filename) print(f) except Exception as e: pass return jsonify({ 'data': { 'status': 'ok', 'url': place } })
if __name__ == '__main__': app.run( host='0.0.0.0', port=9999 )
|
这一步后端比较简单,大概上就是通过request.files.get加上约定的key值(这里是pic)拿到图片,然后调用save保存到相应路径,再将地址返回 而前端我们选择基于axios进行发送,通过axios发送需要进行一些配置 首先来看不通过ajax发送的方式,这会让页面跳转到http://127.0.0.1:9999/uploadfil 上传图片的界面
1 2 3 4
| <form action="http://127.0.0.1:9999/uploadfile" enctype="multipart/form-data" method="post"> <input accept="image" type="file" name="pic" /> <button type="submit">提交</button> </form>
|
而通过ajax发送,则可以直接添加如下事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| let input = document.querySelector('input'); input.addEventListener('change', (eve) => { console.log(eve) let img = eve.target.files[0]; let formData = new FormData(); formData.append('pic', img) console.log(formData.get('pic')) let config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, onUploadProgress: e => { console.log(e) } }
axios.post("http://127.0.0.1:9999/uploadfile", formData, config) })
|