0

File Uploading is done but not with the same name as filename i have tried this in html file

<html>
 <title>Go upload</title>
 <body>

 <form action="http://localhost:8080/receive" method="post" enctype="multipart/form-data">
 <label for="file">Filename:</label>
 <input type="file" name="file" id="file">
 <input type="submit" name="submit" value="Submit">
 </form>

 </body>
 </html>

and in beego/go receive.go

package main

import (
 "fmt"
 "io"
 "net/http"
 "os"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {

 // the FormFile function takes in the POST input id file
 file, header, err := r.FormFile("file")

 if err != nil {
  fmt.Fprintln(w, err)
  return
 }

 defer file.Close()

 out, err := os.Create("/home/vijay/Desktop/uploadfile")
 if err != nil {
  fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
  return
 }

 defer out.Close()

 // write the content from POST to the file
 _, err = io.Copy(out, file)
 if err != nil {
  fmt.Fprintln(w, err)
 }

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

func main() {
 http.HandleFunc("/", uploadHandler)
 http.ListenAndServe(":8080", nil)
}

i am able to achieve uploading file here with same format... but not with the same name.. now i want this file to be uploaded with same name as file name

Vijay Kumar
  • 597
  • 2
  • 8
  • 27
  • 1
    If the request isn't hitting the server, this code is being executed at all, so there's not much we can help with. Also not sure what beego has to do with this, since you're not importing or using beego for anything. – JimB Aug 31 '15 at 13:24
  • 2
    You're ignoring the error from `http.ListenAndServer`, are you certain that you're only running one server? – JimB Aug 31 '15 at 13:31
  • @JimB, yes only one server is running – Vijay Kumar Sep 01 '15 at 04:33
  • You're naming the new file `uploadfile`. What doesn't work if you use the file name instead? – JimB Sep 01 '15 at 13:47
  • it will show no permission.. since its just directory without uploadFile – Vijay Kumar Sep 03 '15 at 07:18

1 Answers1

7

You are not using a Beego controller to handle the upload

package controllers

import (
        "github.com/astaxie/beego"
)

type MainController struct {
        beego.Controller
}

function (this *MainController) GetFiles() {
    this.TplNames = "aTemplateFile.html"

    file, header, er := this.GetFile("file") // where <<this>> is the controller and <<file>> the id of your form field
    if file != nil {
        // get the filename
        fileName := header.Filename
        // save to server
        err := this.SaveToFile("file", somePathOnServer)
    }
}
Stef K
  • 469
  • 8
  • 13