前端打包下载多个图片(ZIP格式)

前期准备

  1. js库,包括jquery、jszip、FileSaver这三个,可以从网上下载到本地引入,或者直接引用网上的,我这里使用的是后者(以下没有包含jquery,因为本地有)。

<script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.js"></script>
  1. 通用打包方法

var FunLib = {
            // 图片打包下载
            download: function (images, downloadName) {
                FunLib.packageImages(images, downloadName)
            },
            // 打包压缩图片
            packageImages: function (imgs, d
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴为您解答这个问题!以下是能够实现该功能的 Flask 后端和前端代码: 后端代码: ```python from flask import Flask, send_file, request, jsonify import os app = Flask(__name__) @app.route('/download', methods=['POST']) def download(): files = request.files.getlist('files') for file in files: file.save(os.path.join('uploads', file.filename)) return jsonify({'message': 'Files uploaded successfully!'}) @app.route('/get_image/<filename>') def get_image(filename): return send_file(os.path.join('uploads', filename)) ``` 这个后端代码会接收前端传来的多个图片文件,保存到本地的 `uploads` 文件夹中,并且提供一个 API `/get_image/<filename>`,可以通过图片文件名获取图片文件。 前端代码: ```html <!DOCTYPE html> <html> <head> <title>Image Uploader and Downloader</title> </head> <body> <form action="/download" method="POST" enctype="multipart/form-data"> <input type="file" name="files" multiple> <button type="submit">Upload</button> </form> <hr> <div id="images"></div> <button id="download">Download All Images</button> <script> const imagesDiv = document.getElementById('images'); const downloadButton = document.getElementById('download'); fetch('/get_images') .then(response => response.json()) .then(data => { data.forEach(filename => { const img = document.createElement('img'); img.src = `/get_image/${filename}`; imagesDiv.appendChild(img); }); }); downloadButton.addEventListener('click', () => { fetch('/download_all') .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'all_images.zip'; document.body.appendChild(a); a.click(); a.remove(); }); }); </script> </body> </html> ``` 这个前端代码会通过上传文件表单将多个图片文件发送给后端,然后使用 `/get_image/<filename>` API 获取每个图片文件的 URL,并且将图片展示在页面上。当用户点击“Download All Images”按钮时,前端会向后端发送 `/download_all` 请求,后端会将所有图片文件打包一个 ZIP 文件并返回给前端前端会通过浏览器下载这个 ZIP 文件。 希望这个代码可以帮到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值