// UploadToS3 prepares a buffer for upload to S3.
516413
func (s *S3Uploader) UploadToS3(fPath string, buf *bytes.Buffer) error {
	fmt.Fprintf(s.out, "Preparing %q for upload to s3 bucket %q...", filepath.Base(fPath), s.s3url.String())

	req, err := s.buildS3Request(filepath.Base(fPath), buf)
	if err != nil {
		fmt.Fprintln(s.out, " error")
		return err
	}
	fmt.Fprintln(s.out, " done")

	fmt.Fprint(s.out, "Uploading...")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(s.out, " error")
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Fprintln(s.out, " error")
		if resp.StatusCode == 403 {
			fmt.Fprintln(s.out, "Encountered authorization error! Are your keys set correctly?")
		}
		errMsg := fmt.Sprintf("received code %d, should have received %d", resp.StatusCode, http.StatusOK)
		b, err := ioutil.ReadAll(resp.Body)
		if err == nil {
			errMsg = fmt.Sprintf("%s\n\nReceived S3 Response: %q", errMsg, string(b))
		}
		return fmt.Errorf(errMsg)
	}
	fmt.Fprintln(s.out, " done")
	return nil
}
543777
func (f *FS) uploadMultiPart(o *object, r io.Reader) error {

	//chunkSize, err := calcBlockSize(size)
	// if err != nil {
	// 	return err
	// }
	var buf = make([]byte, initialChunkSize)

	var blocks []az.Block
	var rawID uint64

	blob := f.client.GetContainerReference(f.bucket).GetBlobReference(o.name)

	// TODO: performance improvement to mange uploads in separate
	// go-routine than the reader
	for {
		n, err := r.Read(buf)
		if err != nil {
			if err == io.EOF {
				break
			}
			gou.Warnf("unknown err=%v", err)
			return err
		}

		blockID := makeBlockID(rawID)
		chunk := buf[:n]

		if err := blob.PutBlock(blockID, chunk, nil); err != nil {
			return err
		}

		blocks = append(blocks, az.Block{
			ID:     blockID,
			Status: az.BlockStatusLatest,
		})
		rawID++
	}

	err := blob.PutBlockList(blocks, nil)
	if err != nil {
		gou.Warnf("could not put block list %v", err)
		return err
	}

	err = blob.GetProperties(nil)
	if err != nil {
		gou.Warnf("could not load blog properties %v", err)
		return err
	}

	blob.Metadata = o.metadata

	err = blob.SetMetadata(nil)
	if err != nil {
		gou.Warnf("can't set metadata err=%v", err)
		return err
	}
	return nil
}
32039
func (c *Communicator) UploadDir(dst string, src string, exclude []string) error {
	if !strings.HasSuffix(src, "/") {
		dst = fmt.Sprintf("%s\\%s", dst, filepath.Base(src))
	}
	log.Printf("Uploading dir '%s' to '%s'", src, dst)
	wcp, err := c.newCopyClient()
	if err != nil {
		return err
	}
	return wcp.Copy(src, dst)
}
1183095
func (client *SSHClient) Upload(src io.Reader, dst string, size int, mode uint32) error {
	session, err := client.cryptoClient.NewSession()
	if err != nil {
		return err
	}
	defer session.Close()

	w, err := session.StdinPipe()
	if err != nil {
		return err
	}

	errorChan := make(chan error, 2)
	remoteDir := path.Dir(dst)
	remoteFileName := path.Base(dst)

	wg := sync.WaitGroup{}
	wg.Add(2)

	go func() {
		defer w.Close()
		defer wg.Done()

		// Signals to the SSH receiver that content is being passed.
		fmt.Fprintf(w, "C%#o %d %s\n", mode, size, remoteFileName)
		_, err = io.Copy(w, src)
		if err != nil {
			errorChan <- err
			return
		}

		// End SSH transfer
		fmt.Fprint(w, "\x00")
	}()

	go func() {
		defer wg.Done()
		if err := session.Run(fmt.Sprintf("/usr/bin/scp -t %s", remoteDir)); err != nil {
			errorChan <- err
			return
		}
	}()

	wg.Wait()

	select {
	case err := <-errorChan:
		return err
	default:
		break
	}

	return nil
}
225986
func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (*RespMediaUpload, error) {
	req, err := http.NewRequest("POST", cli.BuildBaseURL("_matrix/media/r0/upload"), content)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", contentType)
	req.ContentLength = contentLength
	res, err := cli.Client.Do(req)
	if res != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return nil, err
	}
	if res.StatusCode != 200 {
		contents, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return nil, HTTPError{
				Message: "Upload request failed - Failed to read response body: " + err.Error(),
				Code:    res.StatusCode,
			}
		}
		return nil, HTTPError{
			Message: "Upload request failed: " + string(contents),
			Code:    res.StatusCode,
		}
	}
	var m RespMediaUpload
	if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
		return nil, err
	}
	return &m, nil
}
880669
func (c *Client) UploadToContainer(id string, opts UploadToContainerOptions) error {
	url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts)

	return c.stream("PUT", url, streamOptions{
		in:      opts.InputStream,
		context: opts.Context,
	})
}
914706
func (s *Location) SetS3(v []*CodeGenNodeArg) *Location {
	s.S3 = v
	return s
}
979864
func (s *FilesystemService) Upload(parent, fname string, input io.Reader) ([]ItemStat, error) {

	servers, err := s.GetULServer()
	if err != nil {
		return nil, err
	}

	if len(servers) < 1 {
		return nil, errors.New("no servers available for upload")
	}

	var bodyBuf bytes.Buffer
	writer := multipart.NewWriter(&bodyBuf)

	part, err := writer.CreateFormFile("file", filepath.Base(fname))
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(part, input)
	if err != nil {
		return nil, err
	}

	err = writer.Close()
	if err != nil {
		return nil, err
	}

	// prepare request
	oldHost := s.c.api.Api.BaseUrl.Host
	s.c.api.Api.BaseUrl.Host = strings.Replace(oldHost, "api.oboom.com", servers[0], 1)

	res := s.c.api.Res("ul")
	res.Payload = &bodyBuf
	res.Headers.Set("Content-Type", writer.FormDataContentType())

	// set  token
	params := map[string]string{
		"token":       s.c.User.session,
		"name_policy": "rename",
		"parent":      parent,
	}

	// do the request
	resp, err := res.FormPost(params)
	arr, err := processResponse(resp, err)
	if err != nil {
		return nil, err
	}
	s.c.api.Api.BaseUrl.Host = oldHost

	var items []ItemStat
	if err = decodeInto(&items, arr[1]); err != nil {
		return nil, err
	}

	return items, nil
}
324908
func (client *Client) UploadPackage(pkg Package, fileToUpload string) (Package, Warnings, error) {
	link, ok := pkg.Links["upload"]
	if !ok {
		return Package{}, nil, ccerror.UploadLinkNotFoundError{PackageGUID: pkg.GUID}
	}

	body, contentType, err := client.createUploadStream(fileToUpload, "bits")
	if err != nil {
		return Package{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		URL:    link.HREF,
		Method: link.Method,
		Body:   body,
	})
	if err != nil {
		return Package{}, nil, err
	}

	request.Header.Set("Content-Type", contentType)

	var responsePackage Package
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &responsePackage,
	}
	err = client.connection.Make(request, &response)

	return responsePackage, response.Warnings, err
}
1148932
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) {
	path := l.path(sessionID)
	_, err := l.uploader.UploadWithContext(ctx, &s3manager.UploadInput{
		Bucket:               aws.String(l.Bucket),
		Key:                  aws.String(path),
		Body:                 reader,
		ServerSideEncryption: aws.String(s3.ServerSideEncryptionAwsKms),
	})
	if err != nil {
		return "", ConvertS3Error(err)
	}
	return fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, l.Bucket, path), nil
}
1119970
func (c *Client) Uploads(url *url.URL) (uploads *UploadsService) {
	uploads = &UploadsService{client: c, URL: url}
	return
}
1306005
func (b *BigIP) UploadBytes(data []byte, filename string) (*Upload, error) {
	r := bytes.NewReader(data)
	size := int64(len(data))
	return b.Upload(r, size, uriShared, uriFileTransfer, uriUploads, filename)
}
37270
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
	bucket, object := c.url2BucketAndObject()
	p := minio.NewPostPolicy()
	if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
		return "", nil, probe.NewError(e)
	}
	if strings.TrimSpace(contentType) != "" || contentType != "" {
		// No need to verify for error here, since we have stripped out spaces.
		p.SetContentType(contentType)
	}
	if e := p.SetBucket(bucket); e != nil {
		return "", nil, probe.NewError(e)
	}
	if isRecursive {
		if e := p.SetKeyStartsWith(object); e != nil {
			return "", nil, probe.NewError(e)
		}
	} else {
		if e := p.SetKey(object); e != nil {
			return "", nil, probe.NewError(e)
		}
	}
	u, m, e := c.api.PresignedPostPolicy(p)
	if e != nil {
		return "", nil, probe.NewError(e)
	}
	return u.String(), m, nil
}
1269881
func (s *LoadBalancerService) UploadSslCert(p *UploadSslCertParams) (*UploadSslCertResponse, error) {
	resp, err := s.cs.newRequest("uploadSslCert", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r UploadSslCertResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
875059
func (c *MockSSHClient) Upload(src io.Reader, dst string, size int, mode uint32) error {
	if c.MockUpload != nil {
		return c.MockUpload(src, dst, size, mode)
	}
	return ErrNotImplemented
}
1160997
func (c Client) uploadPart(ctx context.Context, bucketName, objectName, uploadID string, reader io.Reader,
	partNumber int, md5Base64, sha256Hex string, size int64, sse encrypt.ServerSide) (ObjectPart, error) {
	// Input validation.
	if err := s3utils.CheckValidBucketName(bucketName); err != nil {
		return ObjectPart{}, err
	}
	if err := s3utils.CheckValidObjectName(objectName); err != nil {
		return ObjectPart{}, err
	}
	if size > maxPartSize {
		return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName)
	}
	if size <= -1 {
		return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName)
	}
	if partNumber <= 0 {
		return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.")
	}
	if uploadID == "" {
		return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.")
	}

	// Get resources properly escaped and lined up before using them in http request.
	urlValues := make(url.Values)
	// Set part number.
	urlValues.Set("partNumber", strconv.Itoa(partNumber))
	// Set upload id.
	urlValues.Set("uploadId", uploadID)

	// Set encryption headers, if any.
	customHeader := make(http.Header)
	// https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html
	// Server-side encryption is supported by the S3 Multipart Upload actions.
	// Unless you are using a customer-provided encryption key, you don't need
	// to specify the encryption parameters in each UploadPart request.
	if sse != nil && sse.Type() == encrypt.SSEC {
		sse.Marshal(customHeader)
	}

	reqMetadata := requestMetadata{
		bucketName:       bucketName,
		objectName:       objectName,
		queryValues:      urlValues,
		customHeader:     customHeader,
		contentBody:      reader,
		contentLength:    size,
		contentMD5Base64: md5Base64,
		contentSHA256Hex: sha256Hex,
	}

	// Execute PUT on each part.
	resp, err := c.executeMethod(ctx, "PUT", reqMetadata)
	defer closeResponse(resp)
	if err != nil {
		return ObjectPart{}, err
	}
	if resp != nil {
		if resp.StatusCode != http.StatusOK {
			return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName)
		}
	}
	// Once successfully uploaded, return completed part.
	objPart := ObjectPart{}
	objPart.Size = size
	objPart.PartNumber = partNumber
	// Trim off the odd double quotes from ETag in the beginning and end.
	objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"")
	objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"")
	return objPart, nil
}
898495
func (m *MWApi) Upload(dstFilename string, file io.Reader) error {
	if m.edittoken == "" {
		err := m.GetEditToken()
		if err != nil {
			return err
		}
	}

	query := map[string]string{
		"action":   "upload",
		"filename": dstFilename,
		"token":    m.edittoken,
		"format":   m.format,
	}

	buffer := &bytes.Buffer{}
	writer := multipart.NewWriter(buffer)

	for key, value := range query {
		err := writer.WriteField(key, value)
		if err != nil {
			return err
		}
	}

	part, err := writer.CreateFormFile("file", dstFilename)
	_, err = io.Copy(part, file)
	if err != nil {
		return err
	}

	err = writer.Close()
	if err != nil {
		return err
	}

	request, err := http.NewRequest("POST", m.url.String(), buffer)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", writer.FormDataContentType())
	request.Header.Set("user-agent", m.userAgent)
	if m.UseBasicAuth {
		request.SetBasicAuth(m.BasicAuthUser, m.BasicAuthPass)
	}

	resp, err := m.client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if err = checkError(body); err != nil {
		return err
	}

	var response uploadResponse
	err = json.Unmarshal(body, &response)
	if err != nil {
		return err
	}
	if !(response.Upload.Result == "Success" || response.Upload.Result == "Warning") {
		return errors.New(response.Upload.Result)
	}
	return nil
}