golang 文件分片上传
时间: 2023-10-16 09:07:05 浏览: 147
下面是一个简单的 Golang 文件分片上传的示例代码:
```go
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
)
const chunkSize = 1024 * 1024 // 每个分片的大小
func main() {
file, err := os.Open("file.txt")
if err != nil {
fmt.Println("Failed to open file:", err)
return
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
fmt.Println("Failed to get file info:", err)
return
}
fileSize := fileInfo.Size()
chunkNum := int(fileSize / chunkSize)
if fileSize%chunkSize > 0 {
chunkNum++
}
fmt.Println("File size:", fileSize)
fmt.Println("Chunk size:", chunkSize)
fmt.Println("Chunk num:", chunkNum)
fileReader := bufio.NewReader(file)
for i := 0; i < chunkNum; i++ {
chunk := make([]byte, chunkSize)
n, err := fileReader.Read(chunk)
if err != nil && err != io.EOF {
fmt.Println("Failed to read file:", err)
return
}
url := fmt.Sprintf("http://localhost:8080/upload?index=%d&total=%d", i, chunkNum)
req, err := http.NewRequest("PUT", url, bytes.NewReader(chunk[:n]))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("Failed to upload file:", err)
return
}
fmt.Println("Upload response:", resp.Status)
}
}
```
此示例代码将文件分成固定大小的分片,然后使用 HTTP PUT 请求上传每个分片。在请求中,使用 `index` 和 `total` 参数指定当前分片的索引和总分片数。你需要根据实际情况修改 URL 和其他参数。
阅读全文