Use tempfile instead of buffer to reduce memory usage