Why a tempdir? If you can set the filename in the response a tempfile will be sufficient and much simpler.