0

I'm trying to upload a simple file through a POST request with powershell and i'm having a very hard time with it..

with a regular curl command:

curl.exe -X POST -F file=@C:\Temp\test.txt -F file_name=test1.txt http://192.168.1.29:8081/upload

File test1.txt Uploaded successfully

with Powershell:

$form = @{
        file   = 'C:\Temp\test.txt'
        file_name = 'test3.txt'
    }
Invoke-RestMethod -Uri 'http://192.168.1.29:8081/upload' -Method Post -UseDefaultCredentials -ContentType "multipart/form-data;boundary=------WWAsdasdkalQWEasdaads" -Body $form

Server.go code:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/mux"
)

func UploadFile(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    fileName := r.FormValue("file_name")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()

    f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()
    _, _ = io.WriteString(w, "File "+fileName+" Uploaded successfully")
    fmt.Println("Uploaded file: " + fileName)
    _, _ = io.Copy(f, file)
}

func homeLink(w http.ResponseWriter, r *http.Request) {
    _, _ = fmt.Fprintf(w, "Welcome home!")
}

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/", homeLink)
    router.HandleFunc("/upload", UploadFile).Methods("POST")
    log.Fatal(http.ListenAndServe("192.168.1.29:8081", router))
}

Any idea how i'm supposed to get this working? the server error from this request is: multipart: NextPart: EOF

TomP
  • 67
  • 1
  • 6
  • If it works through curl, this is not a Go issue, it's purely a powershell issue. You can remove the Go code & tag. – Adrian Apr 16 '20 at 19:34
  • Go server is to understand the server side.. – TomP Apr 16 '20 at 19:39
  • Right, but you've already demonstrated the server side works, so it is irrelevant. The issue is in your PowerShell script. – Adrian Apr 16 '20 at 19:44

0 Answers0