Process csv file from upload

Issue

I have a gin application that receives a post request containing a csv file which I want to read without saving it. I’m stuck here trying to read from the post request with the following error message: cannot use file (variable of type *multipart.FileHeader) as io.Reader value in argument to csv.NewReader: missing method Read

file, err := c.FormFile("file")
if err != nil {
    errList["Invalid_body"] = "Unable to get request"
    c.JSON(http.StatusUnprocessableEntity, gin.H{
        "status": http.StatusUnprocessableEntity,
        "error":  errList,
    })
}

r := csv.NewReader(file) // <= Error message

records, err := r.ReadAll()

for _, record := range records {
    fmt.Println(record)
}

Is there a good example that I could use?

Solution

first read the file and header

csvPartFile, csvHeader, openErr := r.FormFile("file")
if openErr != nil {
    // handle error 
}

then read the lines from the file

csvLines, readErr := csv.NewReader(csvPartFile).ReadAll()
if readErr != nil {
  //handle error 
}

you can go through the lines looping through the records

for _, line := range csvLines {
        fmt.Println(line)
    }

Answered By – ganapathydselva

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.