如何将flask中的照片发送到服务器?

问题描述 投票:0回答:1

我正在开发一个网站。我正在获取用户上传的照片并将其发送到烧瓶后端进行处理。如果一切顺利,照片将被添加到数据库中,并重定向到主页。由于用户可以多次上传照片,并且可能会删除照片。我使用数组来捕获更新的照片。

project
|
|___app
|   |
|   |___templates
|   |   |
|   |   |__postAd.html
|   |   |___index.html
|   |
|   |__postAd.py
|   
|
|__main.py

postAd.html

<form
    method="POST"
    class="needs-validation"
    novalidate
    id="form"
    enctype="multipart/form-data"
    action="{{url_for('postAd.post_ad',category=category,subcategory=subcategory)}}"
  >
<input class="form-control" type="file" id="formFileMultiple" name="photo" accept=".jpg,.jpeg,.png" multiple="multiple"/>
      <div class="invalid-feedback">file support:jpg,jpeg,png</div>
      <output class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"
        id="result">
      </output>
<button id="submit-button" class="btn btn-primary" type="submit">submit</button>
</form>
<script>
var submitButton = document.getElementById("submit-button");
form.addEventListener(
  "submit",
  function (event) {
    event.preventDefault();    
    if (!form.checkValidity()) {
      form.classList.add("was-validated");
    } 
    else {
      if (confirm("Are you sure you want to post the ad?")) {       
        sendPhotosToServer();
        form.submit();              
      }
    }
  },
  false
);
const imageInput = document.getElementById("formFileMultiple");
const output = document.querySelector("#result");
const uploadedPhotos = [];
imageInput.addEventListener("change", handleImageUpload);

function handleImageUpload(e) {
  const files = Array.from(e.target.files);
  const number_of_images = files.length;

  for (let i = 0; i < number_of_images; i++) {    
    uploadedPhotos.push(files[i]);
    const picReader = new FileReader();
    picReader.addEventListener("load", (event) => {
      const imgContainer = document.createElement("div");
      imgContainer.className = "col";
      imgContainer.innerHTML = `<div class="card">
                            <div class="image-container">
                                <img src="${event.target.result}" alt="${files[i].name}" class="card-img-top" style="height: 200px;
  object-fit: cover;">
                            </div>
                            <div class="card-body">
                                <button class="btn btn-danger btn-sm delete-btn">Delete</button>
                            </div>
                        </div>
                    `;
      const deleteBtn = imgContainer.querySelector(".delete-btn");
      deleteBtn.addEventListener("click", () => {
        imgContainer.remove();
        const index = uploadedPhotos.indexOf(files[i]);
        if (index > -1) {
          uploadedPhotos.splice(index, 1); // Remove the file from the array
        }
      });
      output.appendChild(imgContainer);      
    });
    picReader.readAsDataURL(files[i]);
  } 
}

async function sendPhotosToServer() {
  const formData = new FormData();

  // Append each photo from uploadedPhotos array to the form data
  uploadedPhotos.forEach((photo, index) => {
    formData.append(`photo_${index}`, photo);
  });
  try {
    const response = await fetch(`/post-ads/${category}/${subcategory}`, {
      method: "POST",
      body: formData,
    });

    if (response.ok) {
      const result = await response.json();
      console.log("Photos uploaded successfully!", result);
    } else {
      console.log("Failed to upload photos.", response.status);
    }
  } catch (error) {
    console.error("Error during photo upload:", error);
    console.log("An error occurred while uploading photos.");
  }
}
</script>

postAd.py

@postAd.route("/post-ads/<category>/<subcategory>", methods=['GET','POST'])
@login_required
def post_ad(category,subcategory):
response = render_template("postAd.html",category=category,subcategory=subcategory))
   if request.method == 'POST':
      photos = request.files.getlist('photo')
      ad = Ad(photos=photos)
      db.session.add(ad)
      db.session.commit()
      flash('post ad successfully!','success')
      return redirect(url_for('index.html'))
   return response

每个广告都属于一个类别、子类别。照片显示在浏览器中,每张照片都有一个删除按钮。当我提交表单时,postAd 永远不会获取 uploadedPhotos 中的照片。它只获取用户最后在浏览器中上传的照片。开发工具中的控制台显示照片上传期间错误:类型错误:尝试获取资源时出现网络错误。上传照片时发生错误。网络选项卡显示提取请求被阻止,NS_binding 在传输下中止。看来该错误与网络安全有关。但我仍在开发中,所以一切都使用 http 而不是 https。有办法解决这个问题吗?

javascript python flask
1个回答
0
投票

我找到了解决办法。数据库未收到所有变量。因此,我包含了用户在表单中输入的所有变量并向后端发送了发布请求。

© www.soinside.com 2019 - 2024. All rights reserved.