Home >Backend Development >Golang >Golang learning web application file processing
With the continuous development of Internet technology, the demand for Web applications is also increasing. In the development process of web applications, it is often necessary to handle file and directory operations, such as uploading files, downloading files, viewing file lists, etc. In the Golang language, file processing is a very basic knowledge point and an indispensable part of developing web applications. This article will introduce how Golang handles file operations in web applications.
1. File operation
File operations in Golang are mainly implemented through the os package. The os package mainly provides the following file and directory operation functions:
1. Create a file or directory
Function name: os.Create(name string) (*os.File, error)
Function purpose :Create a file named name. If the file does not exist, create it. If it exists, clear the file.
Function name: os.Mkdir(name string, perm os.FileMode) error
Function purpose :Create a directory named name, the perm parameter specifies the permissions of the directory
Function name: os.MkdirAll(path string, perm os.FileMode) error
Function purpose: Create a multi-level directory, If the directory already exists, no operation is performed
2. Open the file
Function name: os.Open(name string) (*os.File, error)
Function purpose: open a name is the file named, if the file does not exist, an error will be returned
3. Delete the file or directory
Function name: os.Remove(name string) error
Function purpose: Delete a file named name file or directory, if the file or directory does not exist, an error will be returned
Function name: os.RemoveAll(path string) error
Function purpose: Delete a multi-level directory, if the directory does not exist, then Return error
4. Read directory
Function name: os.ReadDir(dirname string) ([]os.DirEntry, error)
Function purpose: Read all files under directory dirname and Directory information, returns slices of type os.DirEntry
2. File upload
In web applications, file upload is a common functional requirement. The specific implementation method is as follows:
1. First add the input tag of the uploaded file in the HTML form
fefcb30236bdeaaa7714d83e86dc7ebc
<input type="file" name="uploadfile" /> <input type="submit" value="上传文件" />
e083986a812e016ef20466f844ca7465
2. In the back-end code, get the uploaded file information
file, handler, err := r.FormFile("uploadfile")
if err != nil {
//处理错误信息
}
where r is a variable of http.Request type. File information can be obtained through the r.FormFile function. If the acquisition fails, an error message will be returned.
3. Save the uploaded file
out, err := os.Create("./uploads/" handler.Filename)
if err != nil {
//处理错误信息
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
//处理错误信息
}
After obtaining the file information, you need to create an output file, and then write the uploaded file content into the output file through the io.Copy function to complete the file saving operation.
3. File Download
In addition to file upload, file download is also a common functional requirement in Web applications. The specific implementation method is as follows:
1. Through HTTP protocol Send file
filename := "./uploads/examplefile.txt"
f, err := os.Open(filename)
if err != nil {
//处理错误信息
}
defer f.Close()
header := make([]byte, 512)
if _, err := f.Read(header); err != nil {
//处理错误信息
}
fileStat, err := f.Stat()
if err != nil {
//处理错误信息
}
w. Header().Set("Content-Disposition", "attachment; filename=" filename)
w.Header().Set("Content-Type", http.DetectContentType(header))
w.Header ().Set("Content-Length", strconv.FormatInt(fileStat.Size(), 10))
f.Seek(0, 0)
io.Copy(w, f)
In this example, first open the file to be downloaded through the os.Open function, then send the file content and related information through the http protocol, and finally write the file content into the HTTP response body through the io.Copy function to achieve File download operation.
4. File list display
In Web applications, file list display is also a common functional requirement, which can be achieved through the following methods:
1. Get the file in the directory File list
dir, err := os.ReadDir("./uploads")
if err != nil {
//处理错误信息
}
2. Traverse files List and display
for _, d := range dir {
if !d.IsDir() { fmt.Fprintf(w, "<a href="/download?file=%s">%s</a><br>", d.Name(), d.Name()) }
}
In this example, the file list in the specified directory is obtained through the os.ReadDir function, Then the file list is displayed on the Web page through the traversal operation, and the file download link is provided.
5. Summary
Through the introduction of this article, we can see that file operations in Golang language are very basic, but they are essential knowledge points for developing Web applications. File upload, download and list display are common file operation requirements. In actual development, the above methods need to be applied flexibly to meet the needs of web applications.
The above is the detailed content of Golang learning web application file processing. For more information, please follow other related articles on the PHP Chinese website!