github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/api/cloudcontroller/uploads/upload.go (about)

     1  package uploads
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"mime/multipart"
     7  	"path/filepath"
     8  
     9  	"code.cloudfoundry.org/cli/api/cloudcontroller"
    10  )
    11  
    12  func CalculateRequestSize(fileSize int64, path string, fieldName string) (int64, error) {
    13  	body := &bytes.Buffer{}
    14  	form := multipart.NewWriter(body)
    15  
    16  	bpFileName := filepath.Base(path)
    17  
    18  	_, err := form.CreateFormFile(fieldName, bpFileName)
    19  	if err != nil {
    20  		return 0, err
    21  	}
    22  
    23  	err = form.Close()
    24  	if err != nil {
    25  		return 0, err
    26  	}
    27  
    28  	return int64(body.Len()) + fileSize, nil
    29  }
    30  
    31  func CreateMultipartBodyAndHeader(file io.Reader, path string, fieldName string) (string, io.ReadSeeker, <-chan error) {
    32  	writerOutput, writerInput := cloudcontroller.NewPipeBomb()
    33  
    34  	form := multipart.NewWriter(writerInput)
    35  
    36  	writeErrors := make(chan error)
    37  
    38  	go func() {
    39  		defer close(writeErrors)
    40  		defer writerInput.Close()
    41  
    42  		bpFileName := filepath.Base(path)
    43  		writer, err := form.CreateFormFile(fieldName, bpFileName)
    44  		if err != nil {
    45  			writeErrors <- err
    46  			return
    47  		}
    48  
    49  		_, err = io.Copy(writer, file)
    50  		if err != nil {
    51  			writeErrors <- err
    52  			return
    53  		}
    54  
    55  		err = form.Close()
    56  		if err != nil {
    57  			writeErrors <- err
    58  		}
    59  	}()
    60  
    61  	return form.FormDataContentType(), writerOutput, writeErrors
    62  }