Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Created March 12, 2026 15:42
Show Gist options
  • Select an option

  • Save peteristhegreat/36642e9e6e1bf7642c4a7db17fe6a28a to your computer and use it in GitHub Desktop.

Select an option

Save peteristhegreat/36642e9e6e1bf7642c4a7db17fe6a28a to your computer and use it in GitHub Desktop.
7z to make arbitrary zip of a single file for upload/download

Hopefully you have a programming language that supports some sort of native compression scheme for uploads and downloads.

If not, you can use zip/unzip. But what about onto machines that don't have zip/unzip? What about 7zip?

This seems like a lot, but for a single file up and down with compression in a language that doesn't do it for you, it works okay...

This is a serverside rename, zip, upload, then client side download setup.

Given a file you want to zip before uploading, and you want to set the name of the file to be a secure_filename... There are a few steps.

Calculate a secure file name from the basename of the input filename.

https://werkzeug.palletsprojects.com/en/stable/utils/#werkzeug.utils.secure_filename

target_name = secure_filename(basename(input_filename))

7z makes folders internally inside the zip based on the pwd. So if you don't want folders, you have to change to the folder of the target file beforehand.

old_pwd = pwd()
cd(dirname(input_file))  # or use pushd/popd pattern

Rename to the new secure filename.

rename(basename(input_file), target_name))

Do the zip.

output_zip = target_name + ".zip"
run("7z a -tzip -mx=9 \"" + output_zip + "\" \"" + target_name + "\" -y")

# same as
# 7z a -tzip -mx=9 "$output_zip" "$target_name" -y

Undo the rename and the cd.

rename(target_name, basename(input_file)))
cd(old_pwd)  # or popd

Upload the file with s3 or however... presign a link or expose it to the receiver

aws s3 cp $(dirname input_file)/$output_zip s3://bucket_name/path/$output_zip

Upon downloading the file on the client side, how do you unzip it?

Download to a temp directory.

Change the folder to the destination directory.

old_dir = pwd()
cd(dest_dir)

Use 7z again to unzip with the target_name.

7z x $temp_dir/$output_zip -o'.' -y

Change the folder back to where your program typically likes to run.

cd(old_dir)

Clean up the downloaded zip

rm(temp_dir + "/" + output_zip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment