首页 > 解决方案 > 上传图片:在服务器上找不到请求的 URL

问题描述

我对烧瓶很陌生,我正在尝试创建一个简单的图像上传器应用程序。

我已经对照其他指南检查了我的代码如何创建这些类型的应用程序,我的代码看起来还不错,但是当我尝试实际提交图像时,它说“在服务器上找不到请求的 URL” . 我想我的 js 可能有错误,因为控制台没有记录“成功”,但我不知道如何解决这个问题。任何帮助将不胜感激和需要。

我的js和html代码:

$(document).ready(function() {
    $("submission").click(function() {
        var form_data = new FormData($('#submit_file')[0]);
        $.ajax({
            type: 'POST',
            url: '/submit_image',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function(data) {
                console.log("success");
            }

        })
    })
})
<body>
    <h1>Image Upload</h1>
    <form action="/submit_image" id = "submit_file">
        <input type="file" id="image_file" name="image_to_be_uploaded">
        <input type="submit" id="submission">
    </form>
</body>

这是我的 python/flask 代码:

@app.route('/submit_image', methods=['POST'])
def submit_image():
    if request.method == 'POST':
        file_val = request.files['file']
        #if file_val.filename != '':
        file_val.save(file_val.filename)
        return redirect(url_for('index'))

@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413

标签: javascripthtmljqueryajaxflask

解决方案


您的 javascript 代码将永远不会被执行。表单以其标准行为传输。
由于您没有指定属性方法,因此使用 GET 方法传输表单。

<form 
  name="submit_image" 
  action="{{ url_for('submit_image') }}" 
  method="post" 
  enctype="multipart/form-data"
>
  <input type="file" name="image" />
  <input type="submit" />
</form>

根据其名称查询传输的表单数据。

@app.route('/submit_image', methods=['GET', 'POST'])
def submit_image():
    if request.method == 'POST':
        file_val = request.files['image']
        # if file_val.filename != '':
        #   Handle empty filename here!
        file_val.save(file_val.filename)
        return redirect(url_for('index'))
    
    return render_template('submit_image.html')

现在它应该可以在没有 javascript 的情况下工作。

如果您想通过 Javascript 代码发送图像并使用提交按钮,我建议您也使用表单的提交事件。该preventDefault函数抑制表单的标准行为。

$(document).ready(function() {
  $("form[name='submit_image']").submit(function(event) {
    event.preventDefault();
    const formData = new FormData($(this)[0]);
    $.ajax({
      type: $(this).attr("method"),
      url: $(this).attr("action"),
      data: formData,
      contentType: false,
      cache: false,
      processData: false,
      success: function(data) {
        console.log("success");
      }
    });
  });
});

它现在应该可以工作了。


以下代码是如何将文件保存在文件夹中并再次提供它们的示例。您将需要创建一个新文件夹。“<APP_ROOT>/var/app-instance/images”

import os
from flask import (
    current_app,
    redirect, 
    render_template, 
    request, 
    send_from_directory
)
from werkzeug.utils import secure_filename

def allowed_file(filename):
    allowed_extensions = current_app.config.get(
        'ALLOWED_EXTENSIONS',
        { 'png', 'jpg', 'jpeg', 'gif' }
    )
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

@app.route('/submit_image', methods=['GET', 'POST'])
def submit_image():
    dest_folder = current_app.config.get('UPLOAD_FOLDER', 'images')

    if request.method == 'POST':
        if 'image' not in request.files:
            return redirect(request.url)

        file_val = request.files['image']

        if file_val.filename == '':
            return redirect(request.url)
        
        if file_val and allowed_file(file_val.filename):
            dest = os.path.join(
                current_app.instance_path,
                dest_folder,
                secure_filename(file_val.filename))
            file_val.save(dest)

    images = os.listdir(os.path.join(
        current_app.instance_path,
        dest_folder))

    return render_template('submit_image.html', images=images)

@app.route('/serve_image/<path:filename>')
def serve_image(filename):
    dest_folder = current_app.config.get('UPLOAD_FOLDER', 'images')
    return send_from_directory(
        os.path.join(current_app.instance_path, dest_folder),
        filename
    )
<h1>Image Upload</h1>
<form
  name="submit_image"
  action="{{ url_for('submit_image') }}"
  method="post"
  enctype="multipart/form-data"
>
  <input type="file" name="image" accept="image/*" />
  <input type="submit" />
</form>

<table>
  {% for img in images -%}
  <tr>
    <td>
      <img
        src="{{ url_for('serve_image', filename=img) }}"
        style="width: 84px; height: auto;" />
      </td>
    <td>
      <a
        href="{{ url_for('serve_image', filename=img) }}"
        target="_blank"
      >{{ img }}</a>
    </td>
  </tr>
  {% endfor -%}
</table>

推荐阅读