简体   繁体   English

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

[英]Upload image to folder with Flask

I have a flask app to let a user upload a picture.我有一个烧瓶应用程序让用户上传图片。 I want to be able to save that picture into a folder.我希望能够将该图片保存到一个文件夹中。 However, the console returns an error.但是,控制台返回错误。 The path is correct, so I am not sure what am I missing:路径是正确的,所以我不确定我错过了什么:

Error:错误:

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

Flask code:烧瓶代码:

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()

I would expect to see the uploaded picture on the upload directory.我希望在上传目录中看到上传的图片。 I want to deploy this to heroku.我想将它部署到heroku。

I think it's an issue with path. 我认为这是路径问题。 just try to replace this line 只是尝试替换这条线

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

I think It'll work. 我认为这会起作用。

This one worked fine for me!这个对我来说很好用!

picture_path = os.path.join(app.root_path, '/Images/uploads/', image.filename) image.save(picture_path) picture_path = os.path.join(app.root_path, '/Images/uploads/', image.filename) image.save(picture_path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM