web图片上传 【flask+vue2】

发布时间 2023-11-23 11:41:50作者: __username

直接上传代码demo

from flask import Flask, request, jsonify
import os
from flask_cors import CORS  # 导入CORS模块

# 文件存储的目录
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 启用CORS
# CORS(app)
CORS(app, resources={r"/*": {"origins": "*"}})  # 允许所有来源

# 设置文件上传大小限制为 16 MB
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return 'Hello World!'


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '上传的非图片'})

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': '没选择图片'})

    if file and allowed_file(file.filename):
        print(file)
        print(file.filename)
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return jsonify({'message': '上传图片成功'})
    else:
        return jsonify({'error': '无效'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
<template>
  <div>
    <input
        type="file"
        ref="fileInput"
        @change="handleFileChange"
    />
    <button @click="uploadFile">上传</button>
  </div>
</template>

<script>
import axios from "axios";
import { Message } from 'element-ui'; // 从 Element UI 导入 Message 组件

export default {
  data() {
    return {
      file: null
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    uploadFile() {
      const formData = new FormData();
      formData.append('file', this.file);

      // 发送文件到后端
      axios.post('http://localhost:5000/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(response => {
            console.log(response.data);
            // 在这里你可以处理上传成功的逻辑
            if ('error' in response.data) {
              Message.success(response.data.error);
              return
            }
            // 显示成功消息
            Message.success(response.data);
          })
          .catch(error => {
            console.error(error);
            // 在这里你可以处理上传失败的逻辑

            // 显示错误消息
            Message.error('文件上传失败');
          });
    }
  }
};
</script>

<style scoped>
/* Add your CSS styles here */
div {
  margin: 20px;
}

input {
  margin-bottom: 10px;
}

button {
  padding: 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style>

效果