0.前言

自己尝试着用Vue+Flask实现了下文件上传下载的功能,初步试验成功可行~

1.后端代码

import os

from flask import Flask, render_template, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config['UPLOAD_FOLDER'] = 'upload'

for file in os.listdir(app.config['UPLOAD_FOLDER']):
    print(file)

@app.route('/file_list', methods = ['GET', 'POST'])
def file_list():
    return jsonify({
        'file_list': [{'name': name} for name in os.listdir(app.config['UPLOAD_FOLDER'])]
    })

@app.route('/download/<string:file_name>', methods = ['POST'])
def download(file_name: str):
    print(file_name)
    print(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
    return send_from_directory(app.config['UPLOAD_FOLDER'], file_name, as_attachment=True)

@app.route('/upload', methods = ['GET', 'POST'])
def uploader():
   if request.method == 'POST':
        print(request.files)
        f = request.files['file']
        print(f.filename)
        print(secure_filename(f.filename))
        # f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
        f.save(os.path.join(app.config['UPLOAD_FOLDER'],f.filename))
        return 'file uploaded successfully'


if __name__ == '__main__':
   app.run()

2.前端代码

<template>
  <div>
    <h3>文件上传</h3>
    <el-upload class="upload-demo" drag action="http://localhost:5000/upload" multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处,或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <el-divider></el-divider>
    <h3>文件下载</h3>
    <p>{{file_list}}</p>
    <el-table
      :data="file_list.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%"
    >
      <el-table-column label="Name" prop="name"></el-table-column>
      <el-table-column align="right">
        <template slot="header" slot-scope="{}">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleDownload(scope.$index, scope.row)">下载</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from "axios";
import fileDownload from 'js-file-download';

export default {
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
        },
      ],
      search: "",
      file_list: "",
    };
  },
  methods: {
    handleDownload(index, row) {
      console.log(index, row);
      const url = "http://localhost:5000/download"
      var path = url + '/' + row['name']
    axios.post(path, {}, {responseType: 'arraybuffer'}).then((res) => {
          fileDownload(res.data, row['name']);
      })

    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    get_file_list(){
        const url = "http://localhost:5000/file_list";
        axios.get(url).then((res) => {
            console.log(res)
            this.file_list = res.data["file_list"];
        }).catch((err) => {
          console.error(err);
        });
    }
  },
  created() {
      this.get_file_list();
  }
};
</script>

<style>
</style>

其中使用了axios、element-ui和js-file-download库。

5.效果

6.参考

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 Volantis 作为主题,总访问量为
载入天数...载入时分秒...
冀ICP备20001334号