This is my code that generates a ZIP file on the fly and writes a pdf (fetched from AWS S3 bucket) inside the ZIP file. If I write the ZIP file to the disk via os.create there is no issues but if I try to send the file via HTTP response I get gibberish data in my Postman response.
func admin_invoice_download_handler_wo_disk(w http.ResponseWriter, r *http.Request) {
fileName := "sample.pdf"
// Initialize AWS S3 Config
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("ap-south-1"),
)
if err != nil {
log.Println("AWS S3 config setup not successful. ", err)
}
// Create S3 service client
client := s3.NewFromConfig(cfg)
result, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String("bucket-name"),
Key: aws.String("bucket-dir/sample.pdf"),
})
if err != nil {
log.Print(err)
}
defer result.Body.Close()
// body in byte
body, err := io.ReadAll(result.Body)
if err != nil {
log.Print(err)
}
// creating a zip
buf := new(bytes.Buffer)
writer := zip.NewWriter(buf)
f, err := writer.Create(fileName)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(body))
if err != nil {
log.Fatal(err)
}
resp1 := &common_tools.MessageResponse{
Message: "Invoice downloaded successfully. ",
}
err = writer.Close()
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Disposition", "attachment; filename=invoices.zip")
w.Header().Set("Content-Type", "application/zip")
io.Copy(w, buf)
json.NewEncoder(w).Encode(resp1)
}
This is the postman response
PKsample.pdf�wT�[�/�l@rVh@@���9眡AB�d�AA2�s�I@�(�$�E2�L���y��w����Z�ǸV��Ԯ���v���U{ê)+��'���`gK;��(�����X�[88ۀ ��N(70k� �6(70/�,.B9Yc��f�/=�����;�7i���eQ��v���� �� A�Qn��V(7��(���l��r���"yg'w��(�����`�o���+.�jXڡ�~�+����n)��p���+�[����SЁ���?t�`8�OI�����B��1�z
����F!���`A>�=A!(�7��~�oє�CtQ���%G���� �����
�
�{���G�`
<�/p����.���, ��ȸ�,�m��d1~ܕ�C�|P~8*�����Pv(��Qs��߉�ں;�~M�X���`�%� ��[�
@q���'����v� ��('w�qvrG9�������i�6����;��w�pGɢ���Q �*����!���삛�+���8#�d��N����ex@M(����B��8��ⳅ1�Jʼn�˸/���Ĥw��.�UݗA��ս�p���Ԁ���S��Xf��mUS����c��=H�Iq�U(5b]���ҳ�}��V宀_i�u�1!J�8'���c.SW�g*���r�Ŧb��C҇o��������_���U��0$��KQ���-*��ٶe<�}���v�(�6Z}����^����������2#����2f�ͶL?b��`*��
�},����e�r�L�4O�d��X�x��b�[1<�cuӨ�)�k��L�P���KU�{�dU� ���3�
�-�-��Օ�l�����G+��u�3d2���%y��>�LT�������B��y@��L�e6T�]��.�]`�|'���2��(����䈩1ҔXAf���x���Kp����S�������F�8�my�Τ�������Qx�*N�iK����p��jD�E�
I tried creating the file on disk via os which works fine but whenever I try to send the same http file via HTTP response I get gibberish data in my Postman Response. I’m expecting a zip file which has my required pdf.
Dhruv Dogra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.