How to save with ioutil.WriteFile in a specific folder?

//this page gives you custom images base64 small for testing
package main

import (
    b64 "encoding/base64"
    "io/ioutil"
  "time"
  "math/rand"
)


func main() {
  data := "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAQAAADa613fAAAAaUlEQVR42u3PQREAAAgDINc/9Izg34MGpJ0XIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiJyWYprx532021aAAAAAElFTkSuQmCC"
    sDec, _ := b64.StdEncoding.DecodeString(data)

  rand.Seed(time.Now().UnixNano())
    ioutil.WriteFile( randSeq(12) +".jpg",sDec, 0644)//this works

  //this dosnt work
  ioutil.TempDir( "img/", randSeq(12) +".jpg") //heres how i need it
}


var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randSeq(n int) string {
    b := make([]rune, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
    }
    return string(b)
}

It should work, assuming the path does actually exist and is writable for the user that has started the program.

Also as a related note: check the returned error value and tell us what it says unless you don’t already understand it on your own…

Dosnt return any error ill try one more time tonight but is weird that this code dosnt works

You can just provide the path, relative or absolute to WriteFile, not sure though what you want with the TempFile…

Do you want to write the file in img/ like img/foo.jpg? Or do you want to first create a temporary directory under img/ and the *then write the file inside this temporary directory like foo/someRandomTempDir/foo.jpg?

1 Like

write the file in img/ like img/foo.jpg

Then just do ioutil.WriteFile("img/foo.jpg", data, mode).

1 Like

Try something like this:

    path := "img/" + randSeq(12) + ".jpg"
    if err := ioutil.WriteFile(path, sDec, 0644); err != nil {
        log.Panic(err)
    }

    fmt.Println(path)

see https://play.golang.org/p/Mi75N2pI_V1

1 Like

what does?

Because func writefile has following signature and it is fairly simple to see that it in fact takes three:

WriteFile(filename string, data []byte, perm os.FileMode) error

1 Like

Yes but it dosnt takes a locations so thats where the problem is, i thought i fixed but no

of course it does take the location, it just this location needs to exist before you write there

By this point im confused for a simple thing mm,
how to make this code with my folder location called img

ioutil.WriteFile(randSeq(12)+".jpg", sDec, 0644)

You where right i was just confused this is how it works

ioutil.WriteFile("img/"+randSeq(12)+".jpg", sDec, 0644)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.