我需要获取从前端接收后端的某些文件的文件名。后端(在 Go 中实现)将接收文件为io.ReadCloser
. 有没有办法我可以从中提取它io.ReadCloser
?
问问题
325 次
5 回答
4
后端(在 Go 中实现)将接收文件作为 io.ReadCloser。有没有办法从 io.ReadCloser 中提取它?
不。
查看 io.ReadCloser 通过运行提供的方法,go doc io.ReadCloser
并注意没有提供名称的方法。因此,除非您不知道它是一个 io.ReadCloser,否则您根本无法做到这一点。
于 2021-06-16T05:26:59.547 回答
1
package main
import (
"errors"
"fmt"
"io"
"os"
)
func fatalln(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// hasName interface is an interface that expects types
// that implements it to have "Name() string" method.
type hasName interface {
Name() string
}
func open(name string) (io.ReadCloser, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
// f implements io.ReadCloser interface as *os.File
// has Read and Close methods.
return f, nil
}
func main() {
// rc is of the type io.ReadCloser
rc, err := open("example.txt")
if err != nil {
fatalln(err)
}
defer rc.Close()
// Type assetion to check rc's underlying type has
// a method "Name() string".
f, ok := rc.(hasName)
if !ok {
fatalln(errors.New("type assertion failed"))
}
// Yay, type assertion succeeded. Print the name!
fmt.Println("Name:", f.Name())
}
于 2021-06-16T05:54:51.650 回答
0
这io.ReadCloser
是一个运行时阅读器的阅读器,它在前端将文件发送到后端时从网络读取文件。您必须根据请求本身来获取该文件名。这是一个假设,但在大多数文件上传的情况下,请求是多部分请求。如果你有同样的情况,你可以阅读标题,通常是Content-Disposition
为了识别文件类型。Go nativehttp.Request
具有解析细节的能力。你可以试试这个:
formFile, handler, err := r.FormFile("file") // read file from network with key "file"
defer formFile.Close()
fileName := handler.Filename // Get file name
于 2021-06-16T03:15:53.913 回答
0
通过定义一个嵌入 io.Reader
的接口,您可以预先要求一个Name()
方法:
package main
import (
"fmt"
"io"
"log"
"os"
)
type NamedReadCloser interface {
io.ReadCloser
Name() string
}
func doThings(f NamedReadCloser) error {
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
fmt.Printf("Name: %s, Content: %s\n", f.Name(), b)
return nil
}
func main() {
f, err := os.Open("/etc/hosts")
if err != nil {
log.Fatal("Cannot open file: ", err)
}
err = doThings(f)
if err != nil {
log.Fatal("Error doing things: ", err)
}
}
这仅在传入的内容具有名称方法时才有效,例如*os.File
. 如果没有,那么您尝试做的事情是不可能的。
于 2021-06-16T17:39:23.410 回答
-1
您必须使用Name
方法将其转换为类型:
package main
import (
"io"
"os"
)
func open(name string) (io.ReadCloser, error) {
return os.Open(name)
}
func main() {
c, e := open("file.txt")
if e != nil {
panic(e)
}
defer c.Close()
f := c.(*os.File)
println(f.Name())
}
于 2021-06-16T02:08:21.280 回答