[web] NOT Create file


(ext) #1

Hi,I have the code, the task is to upload the file.
As soon as I click the upload button, the file is not created in the tmp directory, I create the directory manually, I tested it only on the local machine.
Any guesses?

package main

import (
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
)

const (
CONN_HOST = "localhost"
CONN_PORT = "8089"
)

func fileHandler(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
	log.Printf("error getting a file for the provided form key : ", err)
	return
}

defer file.Close()

out, pathError := os.Create("/tmp/uploadedFile")
if pathError != nil {
	log.Printf("error creating a file for writing : ", pathError)
	return
}
defer out.Close()

_, copyFileError := io.Copy(out, file)

if copyFileError != nil {
	log.Printf("error occurred while file copy : ", copyFileError)
}

fmt.Fprintf(w, "File uploaded successfully : "+header.Filename)
}

func index(w http.ResponseWriter, r *http.Request) {
parsedTemplate, _ := template.ParseFiles("templates/upload-file.html")
parsedTemplate.Execute(w, nil)
}

func main() {
http.HandleFunc("/", index)
http.HandleFunc("/upload", fileHandler)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil {
	log.Fatal("error starting http server : ", err)
	return
}
}

(Ashish Shekar) #2

Your code works perfectly for uploading a file inside /tmp dir

you can check your code by doing these changes

out, pathError := os.Create("/tmp/uploadedFile")

to

currDir, _ := os.Getwd() // get current directory path
out, pathError := os.Create(currDir + "/" + header.Filename)

(ext) #3

Works fine now thakyou!