I am posting a csv file as a binary file using Postman REST API client. I need to get the filename of the uploaded file.
Here is a simple example of posting a csv file as binary data and storing the binary data as a csv file.
package main
import ( //"fmt"
"net/http"
"os"
"io"
"log"
"github.com/gorilla/mux"
)
func uploadData(w http.ResponseWriter, req *http.Request) {
file, err := os.Create("hello.csv")
_, err = io.Copy(file, req.Body)
_ = err
}
func main(){
router := mux.NewRouter()
router.HandleFunc("/parse", uploadData).Methods("POST")
log.Fatal(http.ListenAndServe(":8000", router))
}
Since, there is no filename associated with a HTTP request body. You have to send the filename in your URL if you want to get the filename.
package main
import (
"net/http"
"os"
"io"
"log"
"github.com/gorilla/mux"
)
func uploadData(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
file, err := os.Create(params["fileName"])
_, err = io.Copy(file, req.Body)
if err!=nil{
log.Printf("Error while Posting data")
}
}
func main(){
router := mux.NewRouter()
router.HandleFunc("/upload/{fileName}", uploadData).Methods("POST")
log.Fatal(http.ListenAndServe(":8000", router))
}
You could use an encoding, such as form-data
, which includes the filename to upload file with postman. This will help you can send multipart/form-data
request to server. After that you can extract file name from server side.
From server side
func uploadData(w http.ResponseWriter, req *http.Request) {
_, header, _ := req.FormFile("demo")
fmt.Println(header.Filename)
}