GoLang send file via POST request

vladimir :

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\n")
    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?

Fredrik Mårlind :

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\n")

    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)

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

NodeJS: How to Send a file via Request POST

send file with POST request to TelegramBot

I can not send a post request with Golang?

Download a file via a POST request

Python send multiple files via post request

How to send array via postman in POST request

Send button value by post request via jquery

How to send audio file to server via POST request in Java (Android App)?

How to catch stderr output and send messages to a remote log file via a POST request in objective c?

Can't send data in post request via file_get_contents

How to send http post request with an Avro file?

How to send POST request and get file response?

Android - Send local file via HTTP post

Submitting binary data as a file via post request

Java Upload File via HTTP POST request

Passing arguments to a javascript file via POST request

Django: Upload file via POST request

Upload file via POST request without HttpClicent

Post request to Golang API to send JSON and stringy-fied JSON

I can't figure out how to send a file via POST request to https://0x0.st in java

How to send the nested json in POST Request via postman

Send a POST request via Axios to a Firebase Cloud Function

Flask returning 400 error when POST request is send via a XMLHttpRequest

How to send POST request via angular's HttpClient?

Unable to send POST request via HTTP in Angular 4

POST request via requestJS to send Array of JSON Objects and image files

Send POST Request via AWS Lambda in Node.js

How to Send an XML Data Stream via a HTTP Post Request

Send dictionary via http post request from Javascript to python