python flask+vue实现前后端图片上传

python flask+vue实现前后端图片上传

vue代码如下:

<template>
 <div>
    <input type="file"  @change="handleFileChange"/>
  
       <button @click="uploadFile">上传button>
       <br>
      <img :src="imageUrl" v-if="imageUrl">
  div>
template>

<script>
import axios from "axios";

 
export default {
  data() {
    return {
      imageUrl: '',
    };
  },
  methods: {
    handleFileChange(e) {
      this.file=e.target.files[0];
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imageUrl = reader.result;
        this.uploadImage(file);
      };
    },

    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) {
              alert(response.data.error);
              return
            }
            // 显示成功消息
            alert(response.data);
          })
          .catch(error => {
            console.error(error);
            // 在这里你可以处理上传失败的逻辑
 
            // 显示错误消息
            alert('文件上传失败');
          });
    }
  }
};
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>
 

flask后端代码如下:

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)

实现效果如下:python flask+vue实现前后端图片上传_第1张图片

然后会在我们后端代码工作目录下保存图片。

你可能感兴趣的:(python,python,flask,vue.js)