从blob 下载zip文件到本地并解压

def UnzipFile(req: func.HttpRequest) -> func.HttpResponse:

   

    local_download_path="\\temp"

    extract_to = "\\unzip"

    req_body = req.get_json()

    filePath = req_body.get("filePath")

    logging.info(f'filePath:{filePath}')    

    # 创建服务客户端和文件系统客户端

    service_client = get_service_client(os.getenv("CONNECTION_STRING"))

    file_system_client = service_client.get_file_system_client(os.getenv("CONTAINER"))

    logging.info(f'创建服务客户端和文件系统客户端 file_system_client')    

    try:

        # 确保下载目录和解压目录存在

        os.makedirs(os.path.join( os.getcwd(), local_download_path), exist_ok=True)

        os.makedirs(os.path.join( os.getcwd(), extract_to), exist_ok=True)

    except Exception as e:

        logging.info(f'get local file path:{e}')

    try:

        # 下载压缩文件

        local_zip_path = os.path.join( os.getcwd(), local_download_path, os.path.basename(filePath))

        download_file(file_system_client, filePath, local_zip_path)

        extract_to = os.path.join( os.getcwd(), extract_to)

    except Exception as e:

        logging.info(f'download_file failed:{e}')

    logging.info(f'local_zip_path:{local_zip_path}')

    logging.info(f'extract_to:{extract_to}')

    # 解压文件

    unzip_file(local_zip_path, extract_to)

    data = {

        'result': 'success',

        'message': 'process success.',

        'data': [],

        'code': 200

    }

    # 将 Python 字典转换为 JSON 字符串

    json_string = json.dumps(data, indent=4)  # indent 参数用于格式化输出

    return func.HttpResponse(

            json_string,

            status_code=200

    )

def get_service_client(connection_string):

    service_client = DataLakeServiceClient.from_connection_string(connection_string)

    return service_client

def download_file(file_system_client, file_path, local_path):

    try:

        file_client = file_system_client.get_file_client(file_path)

        download = file_client.download_file()

        with open(local_path, "wb") as local_file:

            local_file.write(download.readall())

        print(f"Downloaded file to {local_path}")

    except Exception as e:

        print(e)

       

def unzip_file(zip_path, extract_to):

    with zipfile.ZipFile(zip_path, 'r') as zip_ref:

        zip_ref.extractall(extract_to)

    print(f"Extracted all files to {extract_to}")

可以使用JSZip库来读取zip文件,并使用FileSaver库将文件下载到本地。以下是一个Vue组件示例,该组件读取zip文件并将其中的图片文件解压下载到本地: ```vue <template> <div> <input type="file" @change="selectZipFile"> <button @click="downloadImages">Download Images</button> </div> </template> <script> import JSZip from 'jszip'; import FileSaver from 'file-saver'; export default { name: 'ZipReader', data() { return { zipFile: null, images: [], }; }, methods: { selectZipFile(event) { this.zipFile = event.target.files[0]; }, async downloadImages() { if (!this.zipFile) { alert('Please select a zip file!'); return; } const zip = new JSZip(); const zipFile = await zip.loadAsync(this.zipFile); const imagePromises = []; zipFile.forEach((relativePath, zipEntry) => { if (zipEntry.dir) { return; } const ext = relativePath.split('.').pop(); if (['jpg', 'jpeg', 'png', 'gif'].includes(ext.toLowerCase())) { const imagePromise = zipEntry.async('base64') .then((base64Data) => { this.images.push({ name: zipEntry.name, data: base64Data, }); }); imagePromises.push(imagePromise); } }); await Promise.all(imagePromises); this.images.forEach((image) => { const byteCharacters = atob(image.data); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: 'image/jpeg' }); FileSaver.saveAs(blob, image.name); }); }, }, }; </script> ``` 该组件包含一个input元素,以便用户选择zip文件。当用户选择zip文件后,组件将其加载到JSZip对象中。然后,组件遍历zip文件中的所有文件,并仅选择图片文件。对于每个图片文件,组件将其解码为Base64字符串,并将其添加到images数组中。最后,组件遍历images数组,并使用FileSaver库将每个图像文件下载到本地
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值