Skip to content

Instantly share code, notes, and snippets.

@gialloporpora
Created July 13, 2012 16:00
Show Gist options
  • Save gialloporpora/3105675 to your computer and use it in GitHub Desktop.
Save gialloporpora/3105675 to your computer and use it in GitHub Desktop.
Batch script to obtain the encoded base64 url of a file
@echo off
set tempfile="%~dp0\temp.txt"
set mimetypes=%~dp0mimetypes.txt
REM Extracting the extension of the file
set ext=%~x1_
REM Removing the period for using as correct variable name
set ext=%ext:~1,-1%
REM Load mimetypes from file, if some mimetype is missing update the file mimetypes.txt
REM for any mimetypes is created a variable mime_mimetype, for example mime_png for image/png
for /f "delims== tokens=1,2 eol=#" %%i in (%mimetypes%) do set mime_%%i=%%j
if not defined mime_%ext%% goto mimeundefined
call set contenttype=%%mime_%ext%%%
openssl enc -e -a -in %1 -out %tempfile%
if "%2"=="one" (sed -n "H;${x;s/\n//g;s/.*/data:%contenttype%;base64,&/;p}" %tempfile% > base64.txt) else (sed -e "1{s/.*/data:%contenttype%;base64,&/;}" %tempfile% > base64.txt)
echo Ok, your base64 encoded file is in base64.txt, open it and good luck my friend!
echo.
goto end
:mimeundefined
echo An error occured, mimetype for this file is not defined
echo I am sorry for this inconvenience
echo edit the mimetypes.txt file and add the mimetype for this file's extension (search it with google, your best friend for these kind of issues)
echo.
goto end
:end:
# In this file are collected mime types for files extensions
# Syntax:
# extension=mimetype
# use \/ instead of / in the mimetype
txt=text\/plain
html=text\/html
pdf=application\/pdf
png=image/png
gif=image\/gif
jpg=image\/jpeg
mp3=audio\/mpeg
ogg=audio\/ogg
@gialloporpora
Copy link
Author

Install

Copy the two files above in a folder under your %PATH% folders.
If you don't have openssl and sed installed, please install them. You can find Windows builds of sed on the GnuWin32 project and builds of openssl at openssl.org. You can install them also using the Cygwin emulator.

Usage

base64 nomefile
base64 nomefile one

Using one as addition argument the line break are removed, but be careful that in this case some text editor have problems to open the resulting file if the file to encode is a big file (for example an MP3 audio file).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment