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 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)