使用beego上传相同格式的文件

Vij*_*mar 0 file-upload go beego

文件上传已完成,但没有与我在html文件中尝试过的文件名相同的名称

<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>
Run Code Online (Sandbox Code Playgroud)

并在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)
}
Run Code Online (Sandbox Code Playgroud)

我能够在这里使用相同的格式实现上传文件...但不能使用相同的名称..现在我希望上传的文件与文件名同名

小智 6

您没有使用Beego控制器来处理上传

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)
    }
}
Run Code Online (Sandbox Code Playgroud)