文件上传已完成,但与文件名不同 我在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)
}
我能够在这里以相同的格式上传文件...但不能使用相同的名称.. 现在我想要使用与文件名相同的名称上传此文件
答案 0 :(得分: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)
}
}