• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang s3manager.NewUploader函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/s3/s3manager.NewUploader函数的典型用法代码示例。如果您正苦于以下问题:Golang NewUploader函数的具体用法?Golang NewUploader怎么用?Golang NewUploader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewUploader函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	flag.Parse()
	if *filepath == "" || *bucket == "" {
		fmt.Println("Please specify correct parameters!")
		fmt.Println("You should specify:")
		fmt.Println("-path with path to file you want to upload")
		fmt.Println("-bucket name of bucket in S3 where you want to upload")
		os.Exit(1)
	}

	file, err := os.Open(*filepath)
	if err != nil {
		fmt.Println("Failed to open a file.", err)
		os.Exit(1)
	}

	session := session.New(createConfig())
	service := s3manager.NewUploader(session)

	resp, err := service.Upload(&s3manager.UploadInput{
		Bucket: aws.String(*bucket),
		Key:    aws.String("/" + getFileName(*filepath)),
		Body:   file,
	})
	if err != nil {
		fmt.Println("Failed to upload a file.", err)
		os.Exit(1)
	}

	fmt.Println("---------------------")
	fmt.Println("File was successfully uploaded!")
	fmt.Println("Location:", resp.Location)
}
开发者ID:kennwhite,项目名称:s3-uploader,代码行数:33,代码来源:main.go


示例2: upload

func (this *StorageUtil) upload(fileName string, fileLocation string, fingerPrint string) (string, error) {
	f, err := os.Open(fileLocation)
	defer f.Close()

	if err != nil {
		return "", err
	}

	metadata := map[string]*string{}
	metadata["fingerprint"] = &fingerPrint

	uploader := s3manager.NewUploader(this.ssn)

	result, err := uploader.Upload(&s3manager.UploadInput{
		Bucket:   &this.Bucket,
		Key:      &fileName,
		Body:     f,
		Metadata: metadata,
	})

	if err != nil {
		return "", err
	} else {
		return result.Location, nil
	}
}
开发者ID:hanguofeng,项目名称:nebulachain,代码行数:26,代码来源:storageutil.go


示例3: main

func main() {
	flag.Parse()
	if *filesPath == "" || *bucket == "" {
		fmt.Println("Please specify correct parameters!")
		fmt.Println("You should specify:")
		fmt.Println("-path with path to file you want to upload")
		fmt.Println("-bucket name of bucket in S3 where you want to upload")
		os.Exit(1)
	}

	file, err := os.Open(*filesPath)
	if err != nil {
		log.Fatal("Failed to open a file with an error: ", err)
	}
	defer file.Close()
	info, err := file.Stat()
	if err != nil {
		log.Fatal("Failed to get info about file with an error: ", err)
	}

	session := session.New(createConfig())
	service := s3manager.NewUploader(session)

	switch mode := info.Mode(); {
	case mode.IsDir():
		uploadDirectory(*service, *file)
	case mode.IsRegular():
		uploadFile(*service, *uploadPath+getFileName(*filesPath), file)
	}
}
开发者ID:artemnikitin,项目名称:s3-uploader,代码行数:30,代码来源:main.go


示例4: Update

// Update the Object from in with modTime and size
func (o *Object) Update(in io.Reader, modTime time.Time, size int64) error {
	uploader := s3manager.NewUploader(o.fs.ses, func(u *s3manager.Uploader) {
		u.Concurrency = 2
		u.LeavePartsOnError = false
		u.S3 = o.fs.c
	})

	// Set the mtime in the meta data
	metadata := map[string]*string{
		metaMtime: aws.String(swift.TimeToFloatString(modTime)),
	}

	// Guess the content type
	contentType := fs.MimeType(o)

	key := o.fs.root + o.remote
	req := s3manager.UploadInput{
		Bucket:      &o.fs.bucket,
		ACL:         &o.fs.perm,
		Key:         &key,
		Body:        in,
		ContentType: &contentType,
		Metadata:    metadata,
		//ContentLength: &size,
	}
	_, err := uploader.Upload(&req)
	if err != nil {
		return err
	}

	// Read the metadata from the newly created object
	o.meta = nil // wipe old metadata
	err = o.readMetaData()
	return err
}
开发者ID:greendayo7,项目名称:rclone,代码行数:36,代码来源:s3.go


示例5: Upload

// Upload upload object
func (service Service) Upload(key string, filePath string) error {
	if key == "" {
		return fmt.Errorf("key must be a nonempty string")
	}
	if filePath == "" {
		return fmt.Errorf("filePath must be a nonempty string")
	}

	file, err := os.Open(filePath)
	if err != nil {
		return err
	}

	defer file.Close()
	uploader := s3manager.NewUploader(session.New())
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket:      aws.String(service.bucketSource),
		Key:         aws.String(key),
		ACL:         aws.String(s3.ObjectCannedACLPublicRead),
		ContentType: aws.String(mime.TypeByExtension(path.Ext(key))),
		Body:        file,
	})

	return err
}
开发者ID:get3w,项目名称:get3w,代码行数:26,代码来源:s3.go


示例6: UploadFile

func (client *s3client) UploadFile(bucketName string, remotePath string, localPath string) (string, error) {
	uploader := s3manager.NewUploader(client.session)

	stat, err := os.Stat(localPath)
	if err != nil {
		return "", err
	}

	localFile, err := os.Open(localPath)
	if err != nil {
		return "", err
	}

	defer localFile.Close()

	progress := client.newProgressBar(stat.Size())

	progress.Start()
	defer progress.Finish()

	uploadOutput, err := uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(remotePath),
		Body:   progress.NewProxyReader(localFile),
	})
	if err != nil {
		return "", err
	}

	if uploadOutput.VersionID != nil {
		return *uploadOutput.VersionID, nil
	}

	return "", nil
}
开发者ID:keymon,项目名称:s3-resource,代码行数:35,代码来源:s3client.go


示例7: UploadFile

func (client *s3client) UploadFile(bucketName string, remotePath string, localPath string) (string, error) {
	uploader := s3manager.NewUploader(&s3manager.UploadOptions{
		S3: client.client,
	})

	localFile, err := os.Open(localPath)
	if err != nil {
		return "", err
	}

	defer localFile.Close()

	// uploadOutput, err := uploader.Upload(&s3manager.UploadInput{
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(remotePath),
		Body:   localFile,
	})
	if err != nil {
		return "", err
	}

	// if uploadOutput.VersionID != nil {
	// return *uploadOutput.VersionID, nil
	// }

	return "", nil
}
开发者ID:dgodd,项目名称:ssh-resource,代码行数:28,代码来源:s3client.go


示例8: writeBackupRemote

// Write the local backup file to S3.
// There are no tests for this remote operation
func (b *Backup) writeBackupRemote() {
	s3Conn := session.New(&aws.Config{Region: aws.String(string(b.Config.S3Region))})

	t := time.Unix(b.StartTime, 0)

	b.RemoteFilePath = fmt.Sprintf("%s/%v/%d/%v/%v", b.Config.ObjectPrefix, t.Year(), t.Month(), t.Day(), filepath.Base(b.FullFilename))

	// re-read the compressed file.  There is probably a better way to do this
	localFileContents, err := ioutil.ReadFile(b.FullFilename)
	if err != nil {
		log.Fatalf("[ERR] Could not read compressed file!: %v", err)
	}

	// Create the params to pass into the actual uploader
	params := &s3manager.UploadInput{
		Bucket: &b.Config.S3Bucket,
		Key:    &b.RemoteFilePath,
		Body:   bytes.NewReader(localFileContents),
	}

	if b.Config.S3ServerSideEncryption != "" {
		params.ServerSideEncryption = &b.Config.S3ServerSideEncryption
	}

	if b.Config.S3KmsKeyID != "" {
		params.SSEKMSKeyId = &b.Config.S3KmsKeyID
	}

	log.Printf("[INFO] Uploading %v/%v to S3 in %v", string(b.Config.S3Bucket), b.RemoteFilePath, string(b.Config.S3Region))
	uploader := s3manager.NewUploader(s3Conn)
	_, err = uploader.Upload(params)
	if err != nil {
		log.Fatalf("[ERR] Could not upload to S3!: %v", err)
	}
}
开发者ID:grubernaut,项目名称:consul-snapshot,代码行数:37,代码来源:backup.go


示例9: uploadPackage

func uploadPackage(config *Config) error {
	key := "package.zip"
	uploadfile, err := os.Open(key)
	if err != nil {
		return err
	}

	//rlu := &rateLimitUploader{ fh: uploadfile }

	fmt.Println("Uploading package.zip to", config.S3Bucket, "bucket...")
	uploader := s3manager.NewUploader(session.New())
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: &config.S3Bucket,
		Key:    &key,
		//Body:   rlu,
		Body: uploadfile,
	})

	if err != nil {
		panic(err)
	}

	fmt.Println("Uploaded package.zip to", config.S3Bucket, "bucket.")

	return nil
}
开发者ID:jamesunger,项目名称:saws,代码行数:26,代码来源:saws.go


示例10: Upload

func Upload(conf *Config, file io.Reader, fileName string, isPNG bool) (string, error) {
	s3Config := aws.NewConfig().
		WithCredentials(credentials.NewStaticCredentials(conf.AccessKeyID, conf.SecretAccessKey, ""))

	forcePathStyle := true
	s3Config.S3ForcePathStyle = &forcePathStyle

	if conf.AwsRegion == "" {
		s3Config = s3Config.WithRegion(" ").WithEndpoint(conf.Endpoint)
	} else {
		s3Config = s3Config.WithRegion(conf.AwsRegion)
	}

	sess := session.New(s3Config)

	uploader := s3manager.NewUploader(sess)

	upParams := &s3manager.UploadInput{
		ACL:    aws.String("public-read"),
		Bucket: &conf.BucketName,
		Key:    &fileName,
		Body:   file,
	}

	if isPNG {
		upParams.ContentType = aws.String("image/png")
	}

	result, err := uploader.Upload(upParams)
	if err != nil {
		return "", fmt.Errorf("Failed to upload file, err: %s", err.Error())
	}

	return result.Location, nil
}
开发者ID:cloudfoundry-incubator,项目名称:routing-perf-release,代码行数:35,代码来源:uploader.go


示例11: TestUploadOrderMultiFailureLeaveParts

func TestUploadOrderMultiFailureLeaveParts(t *testing.T) {
	s, ops, _ := loggingSvc(emptyList)
	s.Handlers.Send.PushBack(func(r *service.Request) {
		switch data := r.Data.(type) {
		case *s3.UploadPartOutput:
			if *data.ETag == "ETAG2" {
				r.HTTPResponse.StatusCode = 400
			}
		}
	})

	mgr := s3manager.NewUploader(&s3manager.UploadOptions{
		S3:                s,
		Concurrency:       1,
		LeavePartsOnError: true,
	})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: aws.String("Bucket"),
		Key:    aws.String("Key"),
		Body:   bytes.NewReader(make([]byte, 1024*1024*12)),
	})

	assert.Error(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart"}, *ops)
}
开发者ID:davidwadden,项目名称:lattice-release,代码行数:25,代码来源:upload_test.go


示例12: fileToBucket

func fileToBucket(filename, bucket string) (size int64, err error) {
	defer Track("fileToBucket", Now(), debugOut)

	// Open the file
	file, err := os.Open(filename)
	if err != nil {
		return
	}
	defer file.Close()

	// Get the filesize
	fi, ferr := file.Stat()
	if ferr == nil {
		size = fi.Size()
	}

	// Extract the basename
	baseFilename := filepath.Base(filename)

	// Setup the uploader, and git'r'done
	svc := s3manager.NewUploader(AWSSession)
	_, err = svc.Upload(&s3manager.UploadInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(baseFilename),
		Body:   file,
	})

	return
}
开发者ID:cognusion,项目名称:post2s3,代码行数:29,代码来源:aws.go


示例13: TestUploadFailCleanup

func TestUploadFailCleanup(t *testing.T) {
	svc := s3.New(nil)

	// Break checksum on 2nd part so it fails
	part := 0
	svc.Handlers.Build.PushBack(func(r *request.Request) {
		if r.Operation.Name == "UploadPart" {
			if part == 1 {
				r.HTTPRequest.Header.Set("X-Amz-Content-Sha256", "000")
			}
			part++
		}
	})

	key := "12mb-leave"
	mgr := s3manager.NewUploader(&s3manager.UploadOptions{
		S3:                svc,
		LeavePartsOnError: false,
	})
	_, err := mgr.Upload(&s3manager.UploadInput{
		Bucket: bucketName,
		Key:    &key,
		Body:   bytes.NewReader(integBuf12MB),
	})
	assert.Error(t, err)
	uploadID := ""
	if merr, ok := err.(s3manager.MultiUploadFailure); ok {
		uploadID = merr.UploadID()
	}
	assert.NotEmpty(t, uploadID)

	_, err = svc.ListParts(&s3.ListPartsInput{
		Bucket: bucketName, Key: &key, UploadId: &uploadID})
	assert.Error(t, err)
}
开发者ID:jloper3,项目名称:amazon-ecs-cli,代码行数:35,代码来源:integration_test.go


示例14: handleMultipartForm

func handleMultipartForm(req *http.Request, folderName string) (err error) {
	// 10MB allocated for files
	const _10mb = (1 << 22) * 24
	if err = req.ParseMultipartForm(_10); err != nil {
		return
	}

	uploader := s3manager.NewUploader(sess)
	for _, fileHeaders := range req.MultipartForm.File {
		for _, header := range fileHeaders {
			var file multipart.File
			if file, err = header.Open(); err != nil {
				return
			}

			_, err = uploader.Upload(&s3manager.UploadInput{
				Bucket: aws.String(conf.S3.BucketName),
				Key:    aws.String(fmt.Sprintf("%s/%s", folderName, header.Filename)),
				Body:   file,
			})
			if err != nil {
				return
			}
		}
	}
	return
}
开发者ID:mozilla-services,项目名称:webrtc_logging,代码行数:27,代码来源:main.go


示例15: Save

// Save will upload a file to S3
func (a *Amazon) Save(filepath, filename, mime string, expire bool) (err error) {

	file, err := os.Open(filepath)
	if err != nil {
		return errors.New("problem opening file for s3")
	}
	defer file.Close()

	uploader := s3manager.NewUploader(a.session)

	// default cachecontrol header
	var cache = "public, max-age=31536000"

	// if we want the file to not be cached
	if expire {
		cache = "public, max-age=0"
	}

	params := &s3manager.UploadInput{
		Bucket:               aws.String(config.Settings.Amazon.Bucket),
		Key:                  aws.String(filename),
		Body:                 file,
		ContentType:          aws.String(mime),
		CacheControl:         aws.String(cache),
		ServerSideEncryption: aws.String(s3.ServerSideEncryptionAes256),
	}

	_, err = uploader.Upload(params)

	return

}
开发者ID:eirka,项目名称:eirka-libs,代码行数:33,代码来源:s3.go


示例16: WriteS3Object

// WriteS3Object writes the data to the given key, optionally compressing it first
func WriteS3Object(data []string, config *aws.Config, bucket string, key string, lineSeparator string, compress bool) (string, error) {
	var reader io.Reader

	byteReader := strings.NewReader(strings.Join(data, lineSeparator))

	if compress {
		key = fmt.Sprintf("%v.gz", key)
		pipeReader, pipeWriter := io.Pipe()
		reader = pipeReader

		go func() {
			gw := gzip.NewWriter(pipeWriter)
			io.Copy(gw, byteReader)
			gw.Close()
			pipeWriter.Close()
		}()
	} else {
		reader = byteReader
	}

	uploader := s3manager.NewUploader(session.New(config))

	result, err := uploader.Upload(&s3manager.UploadInput{
		Body:   reader,
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	})

	return result.Location, err
}
开发者ID:dailyburn,项目名称:ratchet,代码行数:31,代码来源:s3.go


示例17: main

func main() {
	if len(os.Args) != 3 {
		log.Fatal("wrong number of arguments")
	}
	src, _ := os.Args[1], os.Args[2]

	creds := credentials.NewEnvCredentials()
	if _, err := creds.Get(); err != nil {
		log.Fatal(err)
	}

	svc := s3.New(&aws.Config{
		Credentials:      creds,
		Region:           "us-east-2",
		Endpoint:         "s3.amazonaws.com",
		S3ForcePathStyle: true,
	})

	uploader := s3manager.NewUploader(&s3manager.UploadOptions{S3: svc})

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				switch event.Op {
				case fsnotify.Create:
					handleCreate(watcher, uploader, event.Name)
				case fsnotify.Write:
					log.Println("modified file:", event.Name)
				}

			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			log.Println(path)
			return watcher.Add(path)
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}

	<-done

}
开发者ID:mattaitchison,项目名称:gofs3,代码行数:59,代码来源:main.go


示例18: newS3Client

// newS3Client returns S3 service client
func newS3Client(cfg *aws.Config) *s3Client {
	return &s3Client{
		region: *cfg.Region,
		client: s3.New(session.New(cfg)),
		uploader: s3manager.NewUploader(session.New(cfg), func(u *s3manager.Uploader) {
			u.PartSize = 64 * 1024 * 1024
		}),
	}
}
开发者ID:lucmichalski,项目名称:s3secrets,代码行数:10,代码来源:s3.go


示例19: uploadSegmentsToS3

func uploadSegmentsToS3(inputFolder string, s3id string, scanned func(string, bool), uploaded func(int, int)) error {
	inputPath := scratchPath(inputFolder)
	sess := session.New(&aws.Config{Region: aws.String("us-west-2")})
	uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) {
		u.PartSize = 5 * 1024 * 1024
		u.Concurrency = 5
	})

	files, err := ioutil.ReadDir(inputPath)
	if err != nil {
		return err
	}

	sort.Sort(ForPlayback(files))

	totalFiles := len(files)
	finishedFiles := make(chan string, len(files))
	limiter := make(chan int, 10)

	go func() {
		for i := range files {
			file := files[i]
			log.Println("doing file", file.Name())
			limiter <- 0
			go func(fname string) {
				fullpath := filepath.Join(inputPath, fname)
				outpath := filepath.Join("media", s3id, fname)

				file, err := os.Open(fullpath)
				if err != nil {
					scanned("Error opening file for upload", true)
					log.Println("Error opening file for upload", err)
					return
				}

				_, err = uploader.Upload(&s3manager.UploadInput{
					Bucket: aws.String("smick-media-output"),
					Key:    aws.String(outpath),
					Body:   file,
				})
				file.Close()
				os.Remove(fullpath)
				finishedFiles <- fname
				<-limiter
			}(file.Name())
		}
	}()

	for j := 1; j <= totalFiles; j++ {
		fname := <-finishedFiles
		logLine := fmt.Sprintf("Uploaded %s: %d of %d", fname, j, totalFiles)
		scanned(logLine, false)
		uploaded(j, totalFiles)
	}

	return nil
}
开发者ID:omarqazi,项目名称:guide,代码行数:57,代码来源:commands.go


示例20: NewUploader

func NewUploader(c client.ConfigProvider, bucketName string) *S3Uploader {
	m := s3manager.NewUploader(c)

	u := S3Uploader{
		uploader:   m,
		bucketName: bucketName,
	}

	return &u
}
开发者ID:postmates,项目名称:go-triton,代码行数:10,代码来源:uploader.go



注:本文中的github.com/aws/aws-sdk-go/service/s3/s3manager.NewUploader函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang s3manager.NewUploaderWithClient函数代码示例发布时间:2022-05-24
下一篇:
Golang s3manager.NewDownloaderWithClient函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap