// handleUploadFile handles native upload of files
554544
func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) string {
	var c tgbotapi.Chattable
	for _, f := range msg.Extra["file"] {
		fi := f.(config.FileInfo)
		file := tgbotapi.FileBytes{
			Name:  fi.Name,
			Bytes: *fi.Data,
		}
		re := regexp.MustCompile(".(jpg|png)$")
		if re.MatchString(fi.Name) {
			c = tgbotapi.NewPhotoUpload(chatid, file)
		} else {
			c = tgbotapi.NewDocumentUpload(chatid, file)
		}
		_, err := b.c.Send(c)
		if err != nil {
			b.Log.Errorf("file upload failed: %#v", err)
		}
		if fi.Comment != "" {
			if _, err := b.sendMessage(chatid, msg.Username, fi.Comment); err != nil {
				b.Log.Errorf("posting file comment %s failed: %s", fi.Comment, err)
			}
		}
	}
	return ""
}
619537
func (gw *Gateway) handleFilesUpload(fi *config.FileInfo) error {
	client := &http.Client{
		Timeout: time.Second * 5,
	}
	// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
	sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
	url := gw.BridgeValues().General.MediaServerUpload + "/" + sha1sum + "/" + fi.Name

	req, err := http.NewRequest("PUT", url, bytes.NewReader(*fi.Data))
	if err != nil {
		return fmt.Errorf("mediaserver upload failed, could not create request: %#v", err)
	}

	gw.logger.Debugf("mediaserver upload url: %s", url)

	req.Header.Set("Content-Type", "binary/octet-stream")
	_, err = client.Do(req)
	if err != nil {
		return fmt.Errorf("mediaserver upload failed, could not Do request: %#v", err)
	}
	return nil
}
150699
func (api *Client) UploadFileContext(ctx context.Context, params FileUploadParameters) (file *File, err error) {
	// Test if user token is valid. This helps because client.Do doesn't like this for some reason. XXX: More
	// investigation needed, but for now this will do.
	_, err = api.AuthTest()
	if err != nil {
		return nil, err
	}
	if params.Filename == "" {
		return nil, fmt.Errorf("files.upload: FileUploadParameters.Filename is mandatory")
	}
	response := &fileResponseFull{}
	values := url.Values{
		"token": {api.token},
	}
	if params.Filetype != "" {
		values.Add("filetype", params.Filetype)
	}
	if params.Filename != "" {
		values.Add("filename", params.Filename)
	}
	if params.Title != "" {
		values.Add("title", params.Title)
	}
	if params.InitialComment != "" {
		values.Add("initial_comment", params.InitialComment)
	}
	if params.ThreadTimestamp != "" {
		values.Add("thread_ts", params.ThreadTimestamp)
	}
	if len(params.Channels) != 0 {
		values.Add("channels", strings.Join(params.Channels, ","))
	}
	if params.Content != "" {
		values.Add("content", params.Content)
		err = api.postMethod(ctx, "files.upload", values, response)
	} else if params.File != "" {
		err = postLocalWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.File, "file", values, response, api)
	} else if params.Reader != nil {
		err = postWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.Filename, "file", values, params.Reader, response, api)
	}
	if err != nil {
		return nil, err
	}

	return &response.File, response.Err()
}
1218828
func (d *DirectoryUploader) Upload(upload UploadFn) error {
	return filepath.Walk(d.Dir, func(path string, f os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		file, err := Open(path)
		if err != nil {
			return err
		}
		relPath, err := filepath.Rel(d.Dir, path)
		if err != nil {
			return err
		}
		file.Path = filepath.ToSlash(relPath)
		return upload(file)
	})
}
666494
func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request) {

	id, err := extractIDFromPath(r.URL.Path)
	if err != nil {
		handler.sendError(w, r, err)
		return
	}

	if handler.composer.UsesLocker {
		locker := handler.composer.Locker
		if err := locker.LockUpload(id); err != nil {
			handler.sendError(w, r, err)
			return
		}

		defer locker.UnlockUpload(id)
	}

	info, err := handler.composer.Core.GetInfo(id)
	if err != nil {
		handler.sendError(w, r, err)
		return
	}

	// Add Upload-Concat header if possible
	if info.IsPartial {
		w.Header().Set("Upload-Concat", "partial")
	}

	if info.IsFinal {
		v := "final;"
		for _, uploadID := range info.PartialUploads {
			v += handler.absFileURL(r, uploadID) + " "
		}
		// Remove trailing space
		v = v[:len(v)-1]

		w.Header().Set("Upload-Concat", v)
	}

	if len(info.MetaData) != 0 {
		w.Header().Set("Upload-Metadata", SerializeMetadataHeader(info.MetaData))
	}

	if info.SizeIsDeferred {
		w.Header().Set("Upload-Defer-Length", UploadLengthDeferred)
	} else {
		w.Header().Set("Upload-Length", strconv.FormatInt(info.Size, 10))
	}

	w.Header().Set("Cache-Control", "no-store")
	w.Header().Set("Upload-Offset", strconv.FormatInt(info.Offset, 10))
	handler.sendResp(w, r, http.StatusOK)
}
168476
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
	content := bytes.NewReader(*fi.Data)
	sp := strings.Split(fi.Name, ".")
	mtype := mime.TypeByExtension("." + sp[len(sp)-1])
	if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
		return
	}
	if fi.Comment != "" {
		_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	} else {
		// image and video uploads send no username, we have to do this ourself here #715
		_, err := b.mc.SendText(channel, msg.Username)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	}
	b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
	res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
	if err != nil {
		b.Log.Errorf("file upload failed: %#v", err)
		return
	}

	switch {
	case strings.Contains(mtype, "video"):
		b.Log.Debugf("sendVideo %s", res.ContentURI)
		_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendVideo failed: %#v", err)
		}
	case strings.Contains(mtype, "image"):
		b.Log.Debugf("sendImage %s", res.ContentURI)
		_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendImage failed: %#v", err)
		}
	}
	b.Log.Debugf("result: %#v", res)
}
131673
func (cs *CachableSource) HandleChange(kind fsutil.ChangeKind, p string, fi os.FileInfo, err error) (retErr error) {
	cs.mu.Lock()
	if cs.txn == nil {
		cs.txn = cs.tree.Txn()
	}
	if kind == fsutil.ChangeKindDelete {
		cs.txn.Delete([]byte(p))
		cs.mu.Unlock()
		return
	}

	h, ok := fi.(hashed)
	if !ok {
		cs.mu.Unlock()
		return errors.Errorf("invalid fileinfo: %s", p)
	}

	hfi := &fileInfo{
		sum: h.Digest().Hex(),
	}
	cs.txn.Insert([]byte(p), hfi)
	cs.mu.Unlock()
	return nil
}
1192370
func (s *backupBlobStorage) AddFile(id string, file io.Reader, size int64) error {
	return s.storeImpl.PutForBucket(s.modelUUID, s.path(id), file, size)
}
84121
func UpHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		updater.Update(nil)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
294506
func (u *ConcurrentUploader) Upload(name string, src isolatedclient.Source, ps *isolatedclient.PushState, done func()) {
	u.wg.Add(1)
	go u.upload(name, src, ps, done)
}
453961
func (sl *Slack) FilesUpload(opt *FilesUploadOpt) (file *UploadedFile, err error) {
	req, err := sl.createFilesUploadRequest(opt)

	if err != nil {
		return
	}

	body, err := sl.DoRequest(req)

	if err != nil {
		return
	}

	res := new(FilesUploadAPIResponse)
	err = json.Unmarshal(body, res)

	if err != nil {
		return
	}

	if res.Ok {
		file = &res.File
	} else {
		err = errors.New(res.Error)
	}

	return
}
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())
}
313751
func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request, name string) (int, error) {

	location := name

	// Prevent absolute path access on Windows.
	// TODO remove when stdlib http.Dir fixes this.
	if runtime.GOOS == "windows" {
		if filepath.IsAbs(name[1:]) {
			return http.StatusNotFound, nil
		}
	}

	f, err := fs.Root.Open(name)
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Likely the server is under load and ran out of file descriptors
		backoff := int(3 + rand.Int31()%3) // 3–5 seconds to prevent a stampede
		w.Header().Set("Retry-After", strconv.Itoa(backoff))
		return http.StatusServiceUnavailable, err
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Return a different status code than above so as to distinguish these cases
		return http.StatusInternalServerError, err
	}

	// redirect to canonical path
	url := r.URL.Path
	if d.IsDir() {
		// Ensure / at end of directory url
		if !strings.HasSuffix(url, "/") {
			Redirect(w, r, path.Base(url)+"/", http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	} else {
		// Ensure no / at end of file url
		if strings.HasSuffix(url, "/") {
			Redirect(w, r, "../"+path.Base(url), http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	}

	// use contents of an index file, if present, for directory
	if d.IsDir() {
		for _, indexPage := range IndexPages {
			index := strings.TrimSuffix(name, "/") + "/" + indexPage
			ff, err := fs.Root.Open(index)
			if err != nil {
				continue
			}

			// this defer does not leak fds because previous iterations
			// of the loop must have had an err, so nothing to close
			defer ff.Close()

			dd, err := ff.Stat()
			if err != nil {
				ff.Close()
				continue
			}

			// Close previous file - release fd immediately
			f.Close()

			d = dd
			f = ff
			location = index
			break
		}
	}

	// Still a directory? (we didn't find an index file)
	// Return 404 to hide the fact that the folder exists
	if d.IsDir() {
		return http.StatusNotFound, nil
	}

	if fs.IsHidden(d) {
		return http.StatusNotFound, nil
	}

	filename := d.Name()

	for _, encoding := range staticEncodingPriority {
		if !strings.Contains(r.Header.Get("Accept-Encoding"), encoding) {
			continue
		}

		encodedFile, err := fs.Root.Open(location + staticEncoding[encoding])
		if err != nil {
			continue
		}

		encodedFileInfo, err := encodedFile.Stat()
		if err != nil {
			encodedFile.Close()
			continue
		}

		// Close previous file - release fd
		f.Close()

		// Stat is needed for generating valid ETag
		d = encodedFileInfo

		// Encoded file will be served
		f = encodedFile

		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Set("Content-Encoding", encoding)

		defer f.Close()
		break

	}

	// Experimental ETag header
	e := fmt.Sprintf(`W/"%x-%x"`, d.ModTime().Unix(), d.Size())
	w.Header().Set("ETag", e)

	// Note: Errors generated by ServeContent are written immediately
	// to the response. This usually only happens if seeking fails (rare).
	http.ServeContent(w, r, filename, d.ModTime(), f)

	return http.StatusOK, nil
}
1300086
func (bh *S3BackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {
	if bh.readOnly {
		return nil, fmt.Errorf("AddFile cannot be called on read-only backup")
	}

	// Calculate s3 upload part size using the source filesize
	partSizeBytes := s3manager.DefaultUploadPartSize
	if filesize > 0 {
		minimumPartSize := float64(filesize) / float64(s3manager.MaxUploadParts)
		// Round up to ensure large enough partsize
		calculatedPartSizeBytes := int64(math.Ceil(minimumPartSize))
		if calculatedPartSizeBytes > partSizeBytes {
			partSizeBytes = calculatedPartSizeBytes
		}
	}

	reader, writer := io.Pipe()
	bh.waitGroup.Add(1)

	go func() {
		defer bh.waitGroup.Done()
		uploader := s3manager.NewUploaderWithClient(bh.client, func(u *s3manager.Uploader) {
			u.PartSize = partSizeBytes
		})
		object := objName(bh.dir, bh.name, filename)

		var sseOption *string
		if *sse != "" {
			sseOption = sse
		}
		_, err := uploader.Upload(&s3manager.UploadInput{
			Bucket:               bucket,
			Key:                  object,
			Body:                 reader,
			ServerSideEncryption: sseOption,
		})
		if err != nil {
			reader.CloseWithError(err)
			bh.errors.RecordError(err)
		}
	}()

	return writer, nil
}
392546
func (sl *Slack) FindFile(id string) (file *UploadedFile, err error) {
	uv := sl.urlValues()
	uv.Add("file", id)

	body, err := sl.GetRequest(filesInfoApiEndpoint, uv)

	if err != nil {
		return
	}

	res := new(FilesUploadAPIResponse)
	err = json.Unmarshal(body, res)

	if err != nil {
		return
	}

	if res.Ok {
		file = &res.File
	} else {
		err = errors.New("File not found")
	}

	return
}
27388
func sendFile(content_type string, hr HandlerReq) error {
	w, r := hr.w, hr.r
	req_file := path.Join(hr.Dir, hr.File)

	f, err := os.Stat(req_file)
	if err != nil {
		return err
	}

	w.Header().Set("Content-Type", content_type)
	w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
	w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
	http.ServeFile(w, r, req_file)

	return nil
}
1078190
func (c *Files) Upload(in *UploadInput) (out *UploadOutput, err error) {
	body, _, err := c.download("/files/upload", in, in.Reader)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}