从上载处理 csv 文件

我有一个gin应用程序,它收到一个包含csv文件的帖子请求,我想在不保存它的情况下读取该文件。我被困在这里,试图从帖子请求中读取,并显示以下错误消息: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)

}

有没有一个很好的例子,我可以使用?


茅侃侃
浏览 121回答 2
2回答

catspeake

首先读取文件和标头csvPartFile, csvHeader, openErr := r.FormFile("file")if openErr != nil {&nbsp; &nbsp; // handle error&nbsp;}然后从文件中读取行csvLines, readErr := csv.NewReader(csvPartFile).ReadAll()if readErr != nil {&nbsp; //handle error&nbsp;}您可以遍历记录的行for _, line := range csvLines {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(line)&nbsp; &nbsp; }

叮当猫咪

正如其他答案所提到的,你应该先这样做。最新版本的 似乎只返回两个值。这对我有用:Open()gin.Context.FromFile(string)func (c *gin.Context) {&nbsp; &nbsp; file_ptr, err := c.FormFile("file")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(err.Error())&nbsp; &nbsp; &nbsp; &nbsp; c.Status(http.StatusUnprocessableEntity)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; log.Println(file_ptr.Filename)&nbsp; &nbsp; file, err := file_ptr.Open()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(err.Error())&nbsp; &nbsp; &nbsp; &nbsp; c.Status(http.StatusUnprocessableEntity)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; defer file.Close()&nbsp; &nbsp; records, err := csv.NewReader(file).ReadAll()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(err.Error())&nbsp; &nbsp; &nbsp; &nbsp; c.Status(http.StatusUnprocessableEntity)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; for _, line := range records {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(line)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go