ZhangZhihui's Blog  

Problem: You want to upload a file to a web application.

 

Solution: Use the net/http package to create a web application and the io package to read the file.

 

Uploading files is commonly done through HTML forms. You learned that HTML forms have an enctype attribute that specifies the format of the form data. By default, the enctype is set to application/x-www-form-urlencoded . This means that the form data is encoded as a query string. However, if you set the enctype to multipart/form-data , the form data will be encoded as a MIME message. This is the format you need to upload files

Here’s an example. You will create a web application that allows users to upload a file. The web application will display the filename and the file size. The web application will also save the file to the local filesystem:

func main() {
    http.HandleFunc("/upload", upload)
    http.ListenAndServe(":8000", nil)
}

func upload(w http.ResponseWriter, r *http.Request) {
    file, fileHeader, err := r.FormFile("uploadfile")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    fmt.Fprintf(w, "%v", fileHeader.Header)
    f, err := os.OpenFile("./uploaded/"+fileHeader.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    io.Copy(f, file)
}

The first thing you need to do is to get the file from the HTML form. You can do this using the FormFile method. The FormFile method takes the name of the file input element as its argument and returns two values and an error. The first value is the file, an io.ReadCloser , and the second value is the file metadata, a multipart.FileHeader .

Using the file header, get the filename and then create a new file. Then use the io.Copy function to copy the file from the io.ReadCloser to the new file. 

To test this, use curl to post a file to the server form. The syntax for curl is to use the -F (form) option, which will add enctype="multipart/form-data" to the request. The argument to this option is a string with the name of the file form field ( uploadfile ), followed by = and then @ followed by the path to the file to upload:

$ curl -F "uploadfile=@lenna.png" http://localhost:8000/upload

Once you run this command, you should see a file lenna.png created in the .uploaded directory.

 

posted on 2023-10-17 15:00  ZhangZhihuiAAA  阅读(4)  评论(0编辑  收藏  举报