-1

I am currently trying to upload a picture and later on process it. But I am getting an 405 error and I don't know how to fix it.

@app.route('/upload')
def upload():
return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_f():
if request.method == 'POST':
  f = request.files['file']
  f.save(f.filename)
  return 'file uploaded successfully'

The html form

   <html>
   <body>
   <form action = "http://localhost:5000/uploader" method = "POST" 
     enctype = "multipart/form-data">
     <input type = "file" name = "file" />
     <input type = "submit"/>
  </form>   
  </body>
  </html>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gre1234
  • 11
  • 5
  • Probably the issue is in your form, inside upload.html. Can you please add its contents so we can take a look and try to help you? – Magnun Leno Apr 22 '21 at 17:01
  • I added the html form – Gre1234 Apr 22 '21 at 17:16
  • Your code works fine. Have you tried restarting your flask server/process? Maybe you're not using it in debug mode, hence the auto-reload is disabled. Also, it's not recommended to hardcode the URL in the form action, always try to use the `url_for` function: `action="{{ url_for('upload_f') }}"`. – Magnun Leno Apr 22 '21 at 17:48
  • Figured it out it works now. Is there a simple way to make the picture I am uploading a Image object. And how to display it later – Gre1234 Apr 22 '21 at 17:59
  • I'm not sure what you meant by 'image object', but you can serve the uploaded image just like any other static asset in Flask. Just save the uploaded image in your statics folder and use `url_for`. Check this question for more details: https://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask – Magnun Leno Apr 22 '21 at 18:32
  • Thanks for the help so much. I seem not to get it completely grom this article. I am trying to make an endpoint /something/. And can't really work out how to pass that filename into a function in order to later display this image. Can you help somehow? – Gre1234 Apr 23 '21 at 18:18
  • I managed to do such thing `@app.route('/rotate/',methods=['POST']) def rotate(name): return send_from_directory('/img',name)` But again it's giving me not allowed method – Gre1234 Apr 23 '21 at 18:36
  • Sorry @hub-111, but that's an entirely different question and in your comment, you didn't provide enough context for us trying to help you out. I believe it's better to open another question, explain all your scenarios, how you tested, and also provide some error evidence. It's really hard to help you with just a couple of lines like this. – Magnun Leno Apr 23 '21 at 18:45
  • Ok I will try to fix it and the open a new question. Thanks alot for the help, you saved my nerves :) – Gre1234 Apr 23 '21 at 19:07

1 Answers1

0

From Miguel Grinberg's Handling File Uploads With Flask tutorial:

import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename


app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)  # 512 bytes should be enough for a header check
    stream.seek(0)  # reset stream pointer
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
    <hr>
    {% for file in files %}
      <img src="{{ url_for('upload', filename=file) }}" style="width: 64px">
    {% endfor %}
  </body>
</html>
Sellers
  • 143
  • 9