HTTP file upload in the Beego (or other way with golang)

67 Views Asked by At
func (this *MainController) Post() {
    file, header, err := this.GetFile("file")
    if err != nil {
        panic(fmt.Sprintf("failed to get uploaded file: %v", err))
    }
    defer file.Close()

    // Specify the file directory where you want to save the uploaded file
    // Replace "/path/to/file/directory" with your desired directory path
    fileDir := "/pacthOFuploadfile"
    err = os.MkdirAll(fileDir, os.ModePerm)
    if err != nil {
        panic(fmt.Sprintf("failed to create file directory: %v", err))
    }

    filePath := fmt.Sprintf("%s/%s", fileDir, header.Filename)
    out, err := os.Create(filePath)
    if err != nil {
        panic(fmt.Sprintf("failed to create file: %v", err))
    }
    defer out.Close()

    _, err = io.Copy(out, file)
    if err != nil {
        panic(fmt.Sprintf("failed to save file: %v", err))
    }

    this.Ctx.WriteString("File uploaded successfully!")
}

I write this controller to upload the file with Beego, but this is work with multipart/form-data contenet type. On the other hand, I need to upload the files with application/octet-stream content type.

How can I do it?

This code give me 500 error when try with application/octet-stream content type :)

0

There are 0 best solutions below