Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert File to Data URL
#2
Hello

To convert CAD files to a data URL, you can use Python libraries such as base64 and pathlib. Here's a short example:


import base64
from pathlib import Path

def convert_cad_to_data_url(file_path):
    with open(file_path, "rb") as file:
        cad_data = file.read()

    base64_data = base64.b64encode(cad_data).decode("utf-8")
    mime_type = get_mime_type(Path(file_path).suffix.lower())
    data_url = f"data:{mime_type};base64,{base64_data}"

    return data_url

def get_mime_type(file_extension):
    mime_types = {
        ".stl": "application/vnd.ms-pki.stl",
        ".obj": "text/plain",
    }
    return mime_types.get(file_extension, "application/octet-stream")
You can use the convert_cad_to_data_url function by passing the file path as an argument, and it will return the corresponding data URL for the CAD file.

Hope it helps you.
Larz60+ write Jul-08-2023, 01:14 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this fime. Please use BBCode tags on future posts.
Reply


Messages In This Thread
Convert File to Data URL - by michaelnicol - Jul-06-2023, 10:41 PM
RE: Convert File to Data URL - by stevediaz - Jul-07-2023, 10:44 AM
RE: Convert File to Data URL - by michaelnicol - Jul-07-2023, 06:51 PM
RE: Convert File to Data URL - by DeaD_EyE - Jul-08-2023, 11:35 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 1,317 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Python Script to convert Json to CSV file chvsnarayana 8 2,684 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  openpyxl convert data to float jacklee26 13 6,382 Nov-19-2022, 11:59 AM
Last Post: deanhystad
  Convert Excel file into csv with Pipe symbol.. mg24 4 1,435 Oct-18-2022, 02:59 PM
Last Post: Larz60+
  Need Help: Convert .pcl file to .pdf file ManuRaval 6 2,668 Sep-13-2022, 01:31 PM
Last Post: ManuRaval
  Convert nested sample json api data into csv in python shantanu97 3 3,011 May-21-2022, 01:30 PM
Last Post: deanhystad
  Convert legacy print file to XLSX file davidm 1 1,874 Oct-17-2021, 05:08 AM
Last Post: davidm
  How to convert binary data into text? ZYSIA 3 2,724 Jul-16-2021, 04:18 PM
Last Post: deanhystad
  Yahoo_fin, Pandas: how to convert data table structure in csv file detlefschmitt 14 7,982 Feb-15-2021, 12:58 PM
Last Post: detlefschmitt
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,475 Dec-23-2020, 08:04 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020