0

文件上传已完成,但与文件名不同,我在 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>

并在 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)
}

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

4

1 回答 1

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)
    }
}
于 2015-09-05T07:08:33.053 回答