// Upload upload image to vk server, return id
424415
func Upload(path string) (vkutil.Photo, error) {
	api.SetDebug(true)
	api.VkApi.AccessToken = setting.VkAccessToken

	f, err := os.Open(filepath.Join("./data/", path))
	if err != nil {
		return vkutil.Photo{}, err
	}

	return api.PhotosUploadWall(setting.VkGroupID, f)
}
694707
func (web *webAPIHandlers) Upload(w http.ResponseWriter, r *http.Request) {
	ctx := newContext(r, w, "WebUpload")

	defer logger.AuditLog(w, r, "WebUpload", mustGetClaimsFromToken(r))

	objectAPI := web.ObjectAPI()
	if objectAPI == nil {
		writeWebErrorResponse(w, errServerNotInitialized)
		return
	}
	vars := mux.Vars(r)
	bucket := vars["bucket"]
	object := vars["object"]

	claims, owner, authErr := webRequestAuthenticate(r)
	if authErr != nil {
		if authErr == errNoAuthToken {
			// Check if anonymous (non-owner) has access to upload objects.
			if !globalPolicySys.IsAllowed(policy.Args{
				Action:          policy.PutObjectAction,
				BucketName:      bucket,
				ConditionValues: getConditionValues(r, "", ""),
				IsOwner:         false,
				ObjectName:      object,
			}) {
				writeWebErrorResponse(w, errAuthentication)
				return
			}
		} else {
			writeWebErrorResponse(w, authErr)
			return
		}
	}

	// For authenticated users apply IAM policy.
	if authErr == nil {
		if !globalIAMSys.IsAllowed(iampolicy.Args{
			AccountName:     claims.Subject,
			Action:          iampolicy.PutObjectAction,
			BucketName:      bucket,
			ConditionValues: getConditionValues(r, "", claims.Subject),
			IsOwner:         owner,
			ObjectName:      object,
		}) {
			writeWebErrorResponse(w, errAuthentication)
			return
		}
	}

	// Check if bucket is a reserved bucket name or invalid.
	if isReservedOrInvalidBucket(bucket, false) {
		writeWebErrorResponse(w, errInvalidBucketName)
		return
	}

	if globalAutoEncryption && !crypto.SSEC.IsRequested(r.Header) {
		r.Header.Add(crypto.SSEHeader, crypto.SSEAlgorithmAES256)
	}

	// Require Content-Length to be set in the request
	size := r.ContentLength
	if size < 0 {
		writeWebErrorResponse(w, errSizeUnspecified)
		return
	}

	// Extract incoming metadata if any.
	metadata, err := extractMetadata(context.Background(), r)
	if err != nil {
		writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
		return
	}

	var pReader *PutObjReader
	var reader io.Reader = r.Body
	actualSize := size

	hashReader, err := hash.NewReader(reader, size, "", "", actualSize)
	if err != nil {
		writeWebErrorResponse(w, err)
		return
	}
	if objectAPI.IsCompressionSupported() && isCompressible(r.Header, object) && size > 0 {
		// Storing the compression metadata.
		metadata[ReservedMetadataPrefix+"compression"] = compressionAlgorithmV1
		metadata[ReservedMetadataPrefix+"actual-size"] = strconv.FormatInt(size, 10)

		actualReader, err := hash.NewReader(reader, size, "", "", actualSize)
		if err != nil {
			writeWebErrorResponse(w, err)
			return
		}

		// Set compression metrics.
		size = -1 // Since compressed size is un-predictable.
		reader = newSnappyCompressReader(actualReader)
		hashReader, err = hash.NewReader(reader, size, "", "", actualSize)
		if err != nil {
			writeWebErrorResponse(w, err)
			return
		}
	}
	pReader = NewPutObjReader(hashReader, nil, nil)
	// get gateway encryption options
	var opts ObjectOptions
	opts, err = putOpts(ctx, r, bucket, object, metadata)
	if err != nil {
		writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
		return
	}
	if objectAPI.IsEncryptionSupported() {
		if hasServerSideEncryptionHeader(r.Header) && !hasSuffix(object, slashSeparator) { // handle SSE requests
			rawReader := hashReader
			var objectEncryptionKey []byte
			reader, objectEncryptionKey, err = EncryptRequest(hashReader, r, bucket, object, metadata)
			if err != nil {
				writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
				return
			}
			info := ObjectInfo{Size: size}
			hashReader, err = hash.NewReader(reader, info.EncryptedSize(), "", "", size) // do not try to verify encrypted content
			if err != nil {
				writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
				return
			}
			pReader = NewPutObjReader(rawReader, hashReader, objectEncryptionKey)
		}
	}

	// Ensure that metadata does not contain sensitive information
	crypto.RemoveSensitiveEntries(metadata)

	// Deny if WORM is enabled
	if globalWORMEnabled {
		if _, err = objectAPI.GetObjectInfo(ctx, bucket, object, opts); err == nil {
			writeWebErrorResponse(w, errMethodNotAllowed)
			return
		}
	}

	putObject := objectAPI.PutObject
	if !hasServerSideEncryptionHeader(r.Header) && web.CacheAPI() != nil {
		putObject = web.CacheAPI().PutObject
	}
	objInfo, err := putObject(context.Background(), bucket, object, pReader, opts)
	if err != nil {
		writeWebErrorResponse(w, err)
		return
	}
	if objectAPI.IsEncryptionSupported() {
		if crypto.IsEncrypted(objInfo.UserDefined) {
			switch {
			case crypto.S3.IsEncrypted(objInfo.UserDefined):
				w.Header().Set(crypto.SSEHeader, crypto.SSEAlgorithmAES256)
			case crypto.SSEC.IsRequested(r.Header):
				w.Header().Set(crypto.SSECAlgorithm, r.Header.Get(crypto.SSECAlgorithm))
				w.Header().Set(crypto.SSECKeyMD5, r.Header.Get(crypto.SSECKeyMD5))
			}
		}
	}

	// Notify object created event.
	sendEvent(eventArgs{
		EventName:    event.ObjectCreatedPut,
		BucketName:   bucket,
		Object:       objInfo,
		ReqParams:    extractReqParams(r),
		RespElements: extractRespElements(w),
		UserAgent:    r.UserAgent(),
		Host:         handlers.GetSourceIP(r),
	})
}
469091
func (client *Client) CreateImage(args *CreateImageArgs) (imageId string, err error) {
	response := &CreateImageResponse{}
	err = client.Invoke("CreateImage", args, &response)
	if err != nil {
		return "", err
	}
	return response.ImageId, nil
}
727421
func (b *BigIP) UploadFile(f *os.File) (*Upload, error) {
	if strings.HasSuffix(f.Name(), ".iso") {
		err := fmt.Errorf("File must not have .iso extension")
		return nil, err
	}
	info, err := f.Stat()
	if err != nil {
		return nil, err
	}
	return b.Upload(f, info.Size(), uriShared, uriFileTransfer, uriUploads, info.Name())
}
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
}
1075792
func uploadAsset(ctx *context.Context, put *config.Put, artifact artifact.Artifact, kind string, check ResponseChecker) error {
	envBase := fmt.Sprintf("%s_%s_", strings.ToUpper(kind), strings.ToUpper(put.Name))
	username := put.Username
	if username == "" {
		// username not configured: using env
		username = ctx.Env[envBase+"USERNAME"]
	}
	secret := ctx.Env[envBase+"SECRET"]

	// Generate the target url
	targetURL, err := resolveTargetTemplate(ctx, put, artifact)
	if err != nil {
		msg := fmt.Sprintf("%s: error while building the target url", kind)
		log.WithField("instance", put.Name).WithError(err).Error(msg)
		return errors.Wrap(err, msg)
	}

	// Handle the artifact
	asset, err := assetOpen(kind, &artifact)
	if err != nil {
		return err
	}
	defer asset.ReadCloser.Close() // nolint: errcheck

	// The target url needs to contain the artifact name
	if !strings.HasSuffix(targetURL, "/") {
		targetURL += "/"
	}
	targetURL += artifact.Name

	var headers = map[string]string{}
	if put.ChecksumHeader != "" {
		sum, err := artifact.Checksum("sha256")
		if err != nil {
			return err
		}
		headers[put.ChecksumHeader] = sum
	}

	_, err = uploadAssetToServer(ctx, put, targetURL, username, secret, headers, asset, check)
	if err != nil {
		msg := fmt.Sprintf("%s: upload failed", kind)
		log.WithError(err).WithFields(log.Fields{
			"instance": put.Name,
			"username": username,
		}).Error(msg)
		return errors.Wrap(err, msg)
	}

	log.WithFields(log.Fields{
		"instance": put.Name,
		"mode":     put.Mode,
	}).Info("uploaded successful")

	return nil
}
97047
func (client *Client) UploadRichMenuImage(richMenuID, imgPath string) *UploadRichMenuImageCall {
	return &UploadRichMenuImageCall{
		c:          client,
		richMenuID: richMenuID,
		imgPath:    imgPath,
	}
}
40967
func (d Datastore) UploadFile(ctx context.Context, file string, path string, param *soap.Upload) error {
	u, p, err := d.uploadTicket(ctx, path, param)
	if err != nil {
		return err
	}
	return d.Client().UploadFile(ctx, file, u, p)
}
441602
func (v *StorageVol) Upload(stream *Stream, offset, length uint64, flags StorageVolUploadFlags) error {
	var err C.virError
	if C.virStorageVolUploadWrapper(v.ptr, stream.ptr, C.ulonglong(offset),
		C.ulonglong(length), C.uint(flags), &err) == -1 {
		return makeError(&err)
	}
	return nil
}
432306
func (s *Service) uploadFile(fullPath string, data io.Reader, randomPublicId bool) (string, error) {
	// Do not upload empty files
	fi, err := os.Stat(fullPath)
	if err == nil && fi.Size() == 0 {
		return fullPath, nil
		if s.verbose {
			fmt.Println("Not uploading empty file: ", fullPath)
		}
	}
	// First check we have no match before sending an HTTP query
	changedLocally := false
	if s.dbSession != nil {
		publicId := cleanAssetName(fullPath, s.basePathDir, s.prependPath)
		ext := filepath.Ext(fullPath)
		match := &uploadResponse{}
		err := s.col.Find(bson.M{"$or": []bson.M{bson.M{"_id": publicId}, bson.M{"_id": publicId + ext}}}).One(&match)
		if err == nil {
			// Current file checksum
			chk, err := fileChecksum(fullPath)
			if err != nil {
				return fullPath, err
			}
			if chk == match.Checksum {
				if s.verbose {
					fmt.Printf("%s: no local changes\n", fullPath)
				} else {
					fmt.Printf(".")
				}
				return fullPath, nil
			} else {
				if s.verbose {
					fmt.Println("File has changed locally, needs upload")
				} else {
					fmt.Printf("U")
				}
				changedLocally = true
			}
		}
	}
	buf := new(bytes.Buffer)
	w := multipart.NewWriter(buf)

	// Write public ID
	var publicId string
	if !randomPublicId {
		publicId = cleanAssetName(fullPath, s.basePathDir, s.prependPath)
		pi, err := w.CreateFormField("public_id")
		if err != nil {
			return fullPath, err
		}
		pi.Write([]byte(publicId))
	}
	// Write API key
	ak, err := w.CreateFormField("api_key")
	if err != nil {
		return fullPath, err
	}
	ak.Write([]byte(s.apiKey))

	// Write timestamp
	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	ts, err := w.CreateFormField("timestamp")
	if err != nil {
		return fullPath, err
	}
	ts.Write([]byte(timestamp))

	// Write signature
	hash := sha1.New()
	part := fmt.Sprintf("timestamp=%s%s", timestamp, s.apiSecret)
	if !randomPublicId {
		part = fmt.Sprintf("public_id=%s&%s", publicId, part)
	}
	io.WriteString(hash, part)
	signature := fmt.Sprintf("%x", hash.Sum(nil))

	si, err := w.CreateFormField("signature")
	if err != nil {
		return fullPath, err
	}
	si.Write([]byte(signature))

	// Write file field
	fw, err := w.CreateFormFile("file", fullPath)
	if err != nil {
		return fullPath, err
	}
	if data != nil { // file descriptor given
		tmp, err := ioutil.ReadAll(data)
		if err != nil {
			return fullPath, err
		}
		fw.Write(tmp)
	} else { // no file descriptor, try opening the file
		fd, err := os.Open(fullPath)
		if err != nil {
			return fullPath, err
		}
		defer fd.Close()

		_, err = io.Copy(fw, fd)
		if err != nil {
			return fullPath, err
		}
		log.Printf("Uploading %s\n", fullPath)
	}
	// Don't forget to close the multipart writer to get a terminating boundary
	w.Close()
	if s.simulate {
		return fullPath, nil
	}

	upURI := s.uploadURI.String()

	if s.uploadResType == PdfType {
		upURI = strings.Replace(upURI, imageType, pdfType, 1)
	} else if s.uploadResType == VideoType {
		upURI = strings.Replace(upURI, imageType, videoType, 1)
	} else if s.uploadResType == RawType {
		upURI = strings.Replace(upURI, imageType, rawType, 1)
	}
	req, err := http.NewRequest("POST", upURI, buf)
	if err != nil {
		return fullPath, err
	}
	req.Header.Set("Content-Type", w.FormDataContentType())
	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return fullPath, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		// Body is JSON data and looks like:
		// {"public_id":"Downloads/file","version":1369431906,"format":"png","resource_type":"image"}
		dec := json.NewDecoder(resp.Body)
		upInfo := new(uploadResponse)
		if err := dec.Decode(upInfo); err != nil {
			return fullPath, err
		}
		// Write info to db
		if s.dbSession != nil {
			// Compute file's checksum
			chk, err := fileChecksum(fullPath)
			if err != nil {
				return fullPath, err
			}
			upInfo.Id = upInfo.PublicId // Force document id
			upInfo.Checksum = chk
			if changedLocally {
				if err := s.col.Update(bson.M{"_id": upInfo.PublicId}, upInfo); err != nil {
					return fullPath, err
				}
			} else {
				if err := s.col.Insert(upInfo); err != nil {
					return fullPath, err
				}
			}
		}
		return upInfo.PublicId, nil
	} else {
		return fullPath, errors.New("Request error: " + resp.Status)
	}
}
599203
func (d Datastore) Upload(ctx context.Context, f io.Reader, path string, param *soap.Upload) error {
	u, p, err := d.uploadTicket(ctx, path, param)
	if err != nil {
		return err
	}
	return d.Client().Upload(ctx, f, u, p)
}
897860
func UploadFile(client *FlickrClient, path string, optionalParams *UploadParams) (*UploadResponse, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	return UploadReader(client, file, file.Name(), optionalParams)
}
1260793
func (c oauthClient) UploadFile(
	localFilePath string,
	remoteFileName string,
	contentType string,
	md5sum string,
) (wl.Upload, error) {
	fileContents, err := c.readLocalFile(localFilePath)
	if err != nil {
		return wl.Upload{}, err
	}

	initialUploadResp, err := c.createUpload(remoteFileName, contentType, len(fileContents), md5sum)
	uploadID := initialUploadResp.ID

	// Upload actual data using returned URL
	// Do not worry about multi-part upload for now
	err = c.uploadAPart(initialUploadResp.Part, fileContents)
	if err != nil {
		return wl.Upload{}, err
	}

	return c.finishUpload(uploadID)
}
1254139
func UploadSFTP(identityFile, host, dir string, files []string) error {
	sftp := exec.Command("sftp")
	sftp.Stdout = nil
	sftp.Stderr = os.Stderr
	if identityFile != "" {
		sftp.Args = append(sftp.Args, "-i", identityFile)
	}
	sftp.Args = append(sftp.Args, host)
	fmt.Println(">>>", strings.Join(sftp.Args, " "))
	if *DryRunFlag {
		return nil
	}

	stdin, err := sftp.StdinPipe()
	if err != nil {
		return fmt.Errorf("can't create stdin pipe for sftp: %v", err)
	}
	if err := sftp.Start(); err != nil {
		return err
	}
	in := io.MultiWriter(stdin, os.Stdout)
	for _, f := range files {
		fmt.Fprintln(in, "put", f, path.Join(dir, filepath.Base(f)))
	}
	stdin.Close()
	return sftp.Wait()
}
189866
func (c Client) newUploadID(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (uploadID string, err error) {
	// Input validation.
	if err := s3utils.CheckValidBucketName(bucketName); err != nil {
		return "", err
	}
	if err := s3utils.CheckValidObjectName(objectName); err != nil {
		return "", err
	}

	// Initiate multipart upload for an object.
	initMultipartUploadResult, err := c.initiateMultipartUpload(ctx, bucketName, objectName, opts)
	if err != nil {
		return "", err
	}
	return initMultipartUploadResult.UploadID, nil
}
564720
func (c *Client) ImageUpdate(imgID int, label *string, description *string) error {
	args := make(map[string]interface{})
	args["ImageID"] = imgID
	args["label"] = label
	args["description"] = description

	_, err := c.apiCall("image.update", args)
	if err != nil {
		return err
	}

	return nil
}
305796
func (batcher *UploadObjectsIterator) UploadObject() BatchUploadObject {
	object := batcher.Objects[batcher.index]
	return object
}