项目准备
$ vue init webpack-simple vue-demo $ cd vue-demo && cnpm i cnpm i element-ui axios -S
前端代码如下
<template> <div id="app"> <el-upload ref="upload" action="action" :show-file-list="false" :http-request="uploadFile"> <el-button>上传</el-button> </el-upload> <img v-if="imageUrl" :src="imageUrl" alt=""> </div> </template> <script> import axios from "axios"; export default { name: "app", data() { return { imageUrl: "", }; }, methods: { async uploadFile(params) { let form = new FormData(); form.append("file", params.file); const res = await axios.post("http://127.0.0.1:5000/upload", form); console.log(res); this.imageUrl = res.data; }, }, }; </script>
file对象可以直接上传到服务器
使用Flask写的临时的文件上传后台服务代码如下
# -*- coding: utf-8 -*- import os from urllib.parse import urljoin from flask import Flask, request, send_from_directory from flask_cors import CORS import uuid app = Flask(__name__) CORS(app, supports_credentials=True) ###################### # 配置文件 ###################### UPLOAD_FOLDER = 'uploads' if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # 允许的扩展名 ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} # 1M app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 # 检查后缀名是否为允许的文件 def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS # 获取文件名 def random_filename(filename): ext = os.path.splitext(filename)[-1] return uuid.uuid4().hex + ext # 上传文件 @app.route("/upload", methods=['POST']) def upload(): file = request.files.get('file') if file and allowed_file(file.filename): print(file.filename) filename = random_filename(file.filename) filepath = os.path.join(UPLOAD_FOLDER, filename) file.save(os.path.join(app.root_path, filepath)) file_url = urljoin(request.host_url, filepath) return file_url return "not allow ext" # 获取文件 @app.route('/uploads/<path:filename>') def get_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == '__main__': app.run(debug=True)