2016-06-08 3 views
-1

Я пытаюсь загрузить файл с помощью Flask. Вот мой HTML кодКолба: Ничего не соответствует данному URI

<!DOCTYPE html> 
<html> 
<head> 
    <title>Python Starter Application</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <link rel="stylesheet" href="stylesheets/style.css" /> 
</head> 
<body> 
    <form action="/upload"> 
     File input 
     <input type="file" name="InputFile"> 
     <button type="submit" class="btn btn-default">Upload</button> 
    </form> 
</body> 
</html> 

вот моя колба код

import os 
from flask import Flask, request 
import swiftclient 

try: 
    from SimpleHTTPServer import SimpleHTTPRequestHandler as Handler 
    from SocketServer import TCPServer as Server 
except ImportError: 
    from http.server import SimpleHTTPRequestHandler as Handler 
    from http.server import HTTPServer as Server 

app = Flask(__name__) 
# Read port selected by the cloud for our application 
PORT = int(os.getenv('PORT', 8000)) 
# Change current directory to avoid exposure of control files 
os.chdir('static') 

httpd = Server(("", PORT), Handler) 

# connections 
auth_url = ## 
project = ## 
projectId = ## 
region = ## 
userId = ## 
username = ## 
password = ## 
domainId = ## 
domainName = ## 
container_name = ## 

conn = swiftclient.Connection(key=password, 
           authurl=auth_url, 
           auth_version='3', 
           os_options={"project_id": projectId, 
              "user_id": userId, 
              "region_name": region}) 

@app.route('/upload', methods=['GET', 'POST']) 
def upload_file(): 
    file = request.files['InputFile'] 
    file_name = file.filename 
    conn.put_object(container_name, 
        file_name, 
        contents=file_name.read(), 
        content_length=1024) 
    return ''' 
    <html> 
    <title>Upload new File</title> 
    <body> 
    <h1>Successful</h1> 
    </body> 
    </html> 
    ''' 

try: 
    print("Start serving at port %i" % PORT) 
    httpd.serve_forever() 
except KeyboardInterrupt: 
    pass 
httpd.server_close() 

Я пропускаю что-то? Я все еще получаю

Ошибка ответа Код ошибки 404. Сообщение: Файл не найден. Объяснение кода ошибки: 404 = Ничто не соответствует указанному URI.

+0

в вашем виде тега, дать действие = «» и попробуйте еще раз, например, <форма действие = «» method = post enctype = multipart/form-data> –

+0

Он по-прежнему дает мне ту же ошибку. –

+0

Вы, кажется, не запускаете сервер Flask, просто 'httpd'. Кроме того, вы вызываете '.read()' на имя файла, что не имеет смысла. – davidism

ответ

-1

как вы используете флягу я думаю, что лучшим решением было бы флягу решение, как:

def upload_file(): 
    if request.method == 'POST': 
     # check if the post request has the file part 
     if 'file' not in request.files: 
      flash('No file part') 
      return redirect(request.url) 
     file = request.files['file'] 
     # if user does not select file, browser also 
     # submit a empty part without filename 
     if file.filename == '': 
      flash('No selected file') 
      return redirect(request.url) 
     if file and allowed_file(file.filename): 
      filename = secure_filename(file.filename) 
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
      #return to the file or what do you want 
      return redirect(url_for('uploaded_file', 
            filename=filename)) 
Смежные вопросы