使用Flask将图像上传到文件夹

时间:2019-08-09 19:45:57

标签: python flask

我有一个flask应用程序,可以让用户上传图片。我希望能够将该图片保存到文件夹中。但是,控制台返回错误。路径是正确的,所以我不确定我缺少什么:

错误:

/c/UOMDataAnalytics/MINSTP201902DATA4/Homework/VisualizePictures/OldPortsApp/static/Images/uploads/WIN_20140917_095804.JPG

烧瓶代码:

import os
import pandas as pd
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from flask import Flask, jsonify, render_template,make_response,url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from flask import request, redirect

app = Flask(__name__, static_url_path='/static')

UploadDir="/Images/uploads/"

# image upload route
@app.route("/upload-image", methods=["GET", "POST"])
def upload_image():
    app.config["IMAGE_UPLOADS"] = UploadDir

    # print (app.config["IMAGE_UPLOADS"])
    if request.method == "POST":
        if request.files:
            image = request.files["image"]
            image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))        
            print(image.filename)
            return redirect(request.url)
    return render_template("public/upload_image.html")

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

我希望可以在上传目录中看到上传的图片。我想将其部署到heroku。

1 个答案:

答案 0 :(得分:0)

我认为这是路径问题。只是尝试替换此行

image.save(os.path.join(os.path.abspath(__file__),'..', UploadDir, image.filename)).

我认为这会起作用。