dpgu5074 2017-08-07 07:40
浏览 561
已采纳

GoLang通过POST请求发送文件

I am new in GoLang language, and I want to create REST API WebServer for file uploading...

So I am stuck in main function (file uploading) via POST request to my server...

I have this line for calling upload function

router.POST("/upload", UploadFile)

and this is my upload function:

func UploadFile( w http.ResponseWriter, r *http.Request, _ httprouter.Params ) {
    io.WriteString(w, "Upload files
")
    postFile( r.Form.Get("file"), "/uploads" )
}

func postFile(filename string, targetUrl string) error {
    bodyBuf := &bytes.Buffer{}
    bodyWriter := multipart.NewWriter(bodyBuf)

    // this step is very important
    fileWriter, err := bodyWriter.CreateFormFile("file", filename)
    if err != nil {
        fmt.Println("error writing to buffer")
        return err
    }

    // open file handle
    fh, err := os.Open(filename)
    if err != nil {
        fmt.Println("error opening file")
        return err
    }

    //iocopy
    _, err = io.Copy(fileWriter, fh)
    if err != nil {
        panic(err)
    }

    bodyWriter.FormDataContentType()
    bodyWriter.Close()

    return err

}

but I can't see any uploaded files in my /upload/ directory...

So what am I doing wrong?

P.S I am getting second error => error opening file, so I think something wrong in file uploading or getting file from UploadFile function, am I right? If yes, than how I can teancfer or get file from this function to postFile function?

  • 写回答

2条回答 默认 最新

  • dongzhi1949 2017-08-07 07:45
    关注

    os.Open will open a file, since the file doesn't exist you will get an error. Use os.Create instead it will create a new file and open it. (ref: https://golang.org/pkg/os/#Open)

    func Open

    func Open(name string) (*File, error)

    Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

    func Create

    func Create(name string) (*File, error)

    Create creates the named file with mode 0666 (before umask), truncating it if it already exists. If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

    EDIT

    Made a new handler as an example: And also using OpenFile as mentioned by: GoLang send file via POST request

    func Upload(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "Upload files
    ")
    
        file, handler, err := r.FormFile("file")
        if err != nil {
            panic(err) //dont do this
        }
        defer file.Close()
    
        // copy example
        f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            panic(err) //please dont
        }
        defer f.Close()
        io.Copy(f, file)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标