Read a multipart.file uploaded by http request with pdf library in golang

125 views Asked by At

I have tried to parse it directly but it turned the binary of the pdf so I tried this instead: copy the file content from the request into a new file that placed in the same package and read it but it turned the file is empty. Can anyone give some explanation about the logic used to solve this problem? Also let me know if you have any suggestion about the package that I can use

func (c *Client) HandleUpload(writer http.ResponseWriter, request *http.Request) {
    ctx, cancel := c.createContextWithTimeout(TimeoutHandleUpload)
    defer cancel()

    f, _, err := request.FormFile("data")
    if err != nil {
        c.httpError(writer, err)
        return
    }
    defer f.Close()

    err = c.ReadFile(f)
    if err != nil {
        c.httpError(writer, err)
        return
    }

    _ = httputil.WriteObj200(writer, nil)
}


func (c *Client) ReadFile(f multipart.File) (err error) {
    var buf bytes.Buffer
    var file bytes.Buffer

    _, err = io.Copy(&buf, f)
    if err != nil {
        log.Fatal(err)
    }

    if err := os.WriteFile("file.pdf", file.Bytes(), 0666); err != nil {
        log.Fatal(err)
    }

    uploadedFile, err := os.Open("file.pdf")
    if err != nil {
        log.Fatal(err)
    }
    defer uploadedFile.Close()

    _, err = io.Copy(uploadedFile, &file)
    fmt.Println("file")

    absPath, err := filepath.Abs("file.pdf")
    content, err := os.ReadFile(absPath)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(content))
}
0

There are 0 answers