将*multipart.FileHeader的内容读入[]byte

问题描述 投票:0回答:2

如何将 *multipart.FileHeader 中包含的文件的正文/内容读取到 GO 中的字节片 ([]byte) 中。

我唯一需要做的就是将内容读入一个巨大的字节片中,但当然我想要文件的确切大小。 我想之后用 md5 对文件内容进行哈希处理。

// file is a *multipart.FileHeader gotten from http request.
fileContent, _ := file.Open()
var byteContainer []byte
byteContainer = make([]byte, 1000000)
fileContent.Read(byteContainer)
fmt.Println(byteContainer)
file go byte
2个回答
5
投票

尝试ioutil.ReadAll

https://play.golang.org/p/FUgPAZ9w2X

就你的情况而言;

byteContainer, err := ioutil.ReadAll(fileContent) // you may want to handle the error
fmt.Printf("size:%d", len(byteContainer))

您可能还想从

multipart
package docs 查看此示例, https://play.golang.org/p/084tWn65-d


0
投票
func createContextWithFile(filePath string) *gin.Context {
    // Открываем файл
    fmt.Println(filePath)
    file, err := os.Open(filePath)
    if err != nil {
        fmt.Println("Error opening file:", err)
        return nil
    }
    defer file.Close()

    // Создаем пустой HTTP-запрос и ответ
    req, err := http.NewRequest("POST", "/upload", nil)
    if err != nil {
        fmt.Println("Error creating request:", err)
        return nil
    }

    // Создаем объект MultipartWriter и устанавливаем граничное значение
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    req.Header.Set("Content-Type", writer.FormDataContentType())

    // Создаем форму для файла
    filePart, err := writer.CreateFormFile("file", "file.txt")
    if err != nil {
        fmt.Println("Error creating form file:", err)
        return nil
    }

    // Копируем содержимое файла в форму
    _, err = io.Copy(filePart, file)
    if err != nil {
        fmt.Println("Error copying file content:", err)
        return nil
    }

    // Завершаем запись в тело запроса
    err = writer.Close()
    if err != nil {
        fmt.Println("Error closing writer:", err)
        return nil
    }

    // Устанавливаем тело запроса и его длину
    req.Body = io.NopCloser(body)
    req.ContentLength = int64(body.Len())

    w := httptest.NewRecorder()

    // Создаем контекст Gin с прикрепленным файлом
    ginContext, _ := gin.CreateTestContext(w)
    ginContext.Request = req

    return ginContext
}

func main() {

    ginContext := createContextWithFile("test_files/file_success.xlsx")

    if ginContext == nil {
        fmt.Println("Failed to create Gin context")
        return
    }

    // Получаем файл из контекста
    file, err := ginContext.FormFile("file")
    if err != nil {
        fmt.Printf("FormFile error: %s\n", err.Error())
        return
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.