Krish Bhanushali
Krish Bhanushali

Reputation: 170

How to write a directory with a file in golang?

Right now, I am trying to use os.Create but it gives me an error while specifying the path of the file. I have to upload my file from HTML to my file system in a specific directory.

file,err:= c.FormFile("file")
if err!=nil{
    checkErr(err)
}
src, err := file.Open()
if err!=nil{
    checkErr(err)
}
defer src.Close()

abs,err :=filepath.Abs("/dir1/dir2/")
if err!=nil{
    checkErr(err)
}

dst,err := os.Create(abs+"/"+file.Filename)
if err !=nil{
    checkErr(err)
}
defer dst.Close()
if _,err = io.Copy(dst,src); err!=nil{
    checkErr(err)
}

I have to upload the file to dir2. Please help me out. Thank you.

Upvotes: 4

Views: 23979

Answers (2)

unknownerror
unknownerror

Reputation: 83

That is how I did it without using io.Copy(...)

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    cwd, _ := os.Getwd()
    err := os.Mkdir("new-dir", os.ModePerm) // you might want different file access, this suffice for this example
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("Created %s at %s\n", "new-dir", cwd)
    }

    path := filepath.Join(cwd, "new-dir", "test-file.txt")
    newFilePath := filepath.FromSlash(path)
    file, err := os.Create(newFilePath)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    fmt.Printf("File created successfully at %s\n", newFilePath)
}

Upvotes: 0

Thundercat
Thundercat

Reputation: 121129

Use filepath.Join to create the path from the directory dir and the file name.

To protect against a write to an arbitrary location in the file system, clean the path with filepath.Base.

file, err := c.FormFile("file")
if err != nil {
    checkErr(err)
    return
}
src, err := file.Open()
if err != nil {
    checkErr(err)
    return
}
defer src.Close()

dst, err := os.Create(filepath.Join(dir, filepath.Base(file.Filename))) // dir is directory where you want to save file.
if err != nil {
    checkErr(err)
    return
}
defer dst.Close()
if _, err = io.Copy(dst, src); err != nil {
    checkErr(err)
    return
}

Upvotes: 11

Related Questions