vue 和 flask 简单 文件 上传,添加滤镜后返回

点击上传按钮,或者拖拽图片即可上传,上传成功后,在网页上显示图片

后端处理后返回处理后的图片

使用element上传组件,action中是上传的api,drag属性是拖拽上传

上传成功后,服务端返回处理后的图片链接

<template>
  <el-upload
    class="avatar-uploader"
    drag
    action="http://localhost:80/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
  export default {
    name: "up",
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);

        this.$refs.img.src = res
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    /*width: 100%;*/
    height: 100%;
    /*display: block;*/
  }
</style>

后端,使用pil,将图片转为黑白后保存,然后返回图片链接

@app.route("/upload", methods=['post', 'get'])
def upload():
    f = request.files['file']
    print(f.filename)
    f.save(f.filename)

    image_file = Image.open(f.filename)  # open colour image
    image_file = image_file.convert('1')  # convert image to black and white
    path = './static/result.png'
    image_file.save(path)
    return 'http://localhost/static/result.png'

返回base64编码或者文件可能更好一点,但貌似没能成功实现。。。。

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1649686
今日推荐