gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
20.93k stars 1.85k forks source link

The uploaded PDF is empty #698

Closed simaybocu closed 2 years ago

simaybocu commented 2 years ago

I am uploading pdf with this library, the pdf is uploading successfully but it is empty. Can you help me what can I do please?

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 {
        panic(err)
    }
    defer file.Close()

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

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/file", UploadFile).Methods("POST")
    log.Fatal(http.ListenAndServe(":8081", router))
}
andrewpillar commented 2 years ago

When doing the io.Copy you're ignoring the error. Perhaps there is an error occuring when you try writing the file that is being missed. Could this be the cause for the file being empty at upload time?