Original post

How I get a file out a base64string to a multipartfile for a new request?

If you want to build a multipart form part that contains the bytes of a PDF encoded using Base64, try something like this.

package main

import (
        "encoding/base64"
        "fmt"
        "log"
        "mime/multipart"
        "net/textproto"
        "strings"
)

func main() {
        // A minimal PDF, see https://stackoverflow.com/a/17280876.
        pdf := []byte(`%PDF-1.0
1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj
xref
0 4
0000000000 65535 f
0000000010 00000 n
0000000053 00000 n
0000000102 00000 n
trailer<</Size 4/Root 1 0 R>>
startxref
149
%EOF`)

        // Encode it using Base64.
        enc := base64.StdEncoding.EncodeToString(pdf)

        // An io.Writer to collect the created multipart form in.
        w := strings.Builder{}

        // A multipart.Writer wrapping the io.Writer.
        mw := multipart.NewWriter(&w)

        // Crea a form field for the PDF.
        h := make(textproto.MIMEHeader)
        h.Add("Content-Disposition", `form-data; name="pdf"; filename="minimal.pdf"`)
        h.Add("Content-Type", "application/pdf")
        fw, err := mw.CreatePart(h)
        if err != nil {
                log.Panic("failed to create form field")
        }

        // Write the Base64 bytes to the form field.
        fw.Write([]byte(enc))

        // Show the result.
        fmt.Println(w.String())
}

Output:

--971201acb7febe720f35118b6abf6bdb78754b23b92f42cba8d1e79b1b2a
Content-Disposition: form-data; name="pdf"; filename="minimal.pdf"
Content-Type: application/pdf

JVBERi0xLjAKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqIDIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbMyAwIFJdL0NvdW50IDE+PmVuZG9iaiAzIDAgb2JqPDwvVHlwZS9QYWdlL01lZGlhQm94WzAgMCAzIDNdPj5lbmRvYmoKeHJlZgowIDQKMDAwMDAwMDAwMCA2NTUzNSBmCjAwMDAwMDAwMTAgMDAwMDAgbgowMDAwMDAwMDUzIDAwMDAwIG4KMDAwMDAwMDEwMiAwMDAwMCBuCnRyYWlsZXI8PC9TaXplIDQvUm9vdCAxIDAgUj4+CnN0YXJ0eHJlZgoxNDkKJUVPRg==

https://play.golang.org/p/qZYKDEBhERO

I response a base64 string from an api. After decoding I have a pdf in byte available. Now I would like to forward this PDF as multipart.file. e.g. to AWS whatever…

I have finished up to the byte, just don’t know how to make a request object out of it to send it on.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.