0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask 画像アップロード

Last updated at Posted at 2025-04-29

お決まり文

from pathlib import Path
from werkzeug.utils import secure_filename

from flask import send_from_directory

app.config['UPLOAD_FOLDER'] = '/path/to/uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB 制限
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

[html]画像アップロード画面

<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
</form>

ファイルアップロード処理

ファイル拡張子が。".jpeg"/ ".png"かチェック
def allowed_file(filename):
    # 拡張子をチェック(ドットがあって許可リスト内か)
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 
ファイルサイズ指定
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
アップロードするファイルのセキュリティ強化
filename = secure_filename(file.filename)
アップロードフォルダ"upload"がなかったらフォルダ作成
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
アップロードしたファイル表示
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
mypageでファイルアップロード処理
def upload():
    if request.method == 'POST':
    
        if 'file' not in request.files:
        # アップロード時、ファイル選ばれてない
            flash('ファイルがありません')
        return redirect(url_for('mypage'))

    file = request.files['image']
    # 画像として読み込み

    if file.filename == "":
        # 画像に、ファイル名なし
        flash("ファイル not found")
        return redirect(url_for('mypage'))

    if file and allowed_file(img.filename):
        filename = secure_filename(file.filename)

        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)  # 保存処理
    return redirect(url_for('uploaded_file', filename=filename))
    # GET時はアップロードフォームを表示
    return render_template('mypage.html')

ファイルアップロードでSQLAcademy使う時

   画像名
   アップロード日時
   ユーザー名
   ユーザーid がいる

宿題

スクショ html 自動 PDF化
web html PDF化 : WeasyPrint
from weasyprint import HTML
HTML('<img src="static/uploaded.png">').write_pdf("output.pdf")
html 自動 PDF化 ロジックヒント

フォームのテキストをHTMLに変えて渡す
文字サイズやレイアウトを変える

class DataForm(FlaskForm):
    content = TextAreaField('内容', validators=[DataRequired()])
    submit = SubmitField('PDF作成')

<form method="POST">
    {{ form.csrf_token }}
    {{ form.content.label }}<br>
    {{ form.content(rows=10, cols=50) }}<br>
    {{ form.submit() }}
</form>

@app.route('/pdf', methods=['GET', 'POST'])
def create_pdf():
    form = DataForm()
    if form.validate_on_submit():
        text = form.content.data
        # この text を HTML に入れて WeasyPrint などで PDF 化
たくさんスクショ 自動でPDF "img2pdf"
from flask import Flask, send_file
import img2pdf

app = Flask(__name__)

@app.route("/download-pdf")
def download_pdf():
    with open("image.png", "rb") as img_file:
        pdf_bytes = img2pdf.convert(img_file)

    with open("output.pdf", "wb") as f:
        f.write(pdf_bytes)

    return send_file("output.pdf", as_attachment=True)

後で勉強用

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?