// MultipartForm is the parsed multipart form, including file uploads.
357634
func (c *Context) MultipartForm() (*multipart.Form, error) {
	err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
	return c.Request.MultipartForm, err
}
730054
func UploadFile(c *middleware.Context) {
	if c.Req.Method == "POST" {
		// 32MiB
		e := c.Req.ParseMultipartForm(32 << 30)
		if e != nil {
			color.Red("%s", e)
			return
		}

		file, info, e := c.Req.FormFile("file")
		if e != nil {
			color.Red("%s", e)
			return
		}
		defer file.Close()

		bts, err := ioutil.ReadAll(file)
		if err != nil {
			c.Error(200, err.Error())
			return
		}

		f, err := models.Upload(info.Filename, bts)
		if err != nil {
			c.Error(200, err.Error())
			return
		}

		c.Data["uploaded"] = f
		c.Redirect("/files/upload/new?uploaded=" + fmt.Sprint(f.BlobID))
		return
	}

	if id := c.QueryInt("uploaded"); id != 0 {
		c.Data["uploaded"] = id

	}
	c.HTML(200, "files/new")
}
222482
func (l *ossObjects) CompleteMultipartUpload(ctx context.Context, bucket, object, uploadID string, uploadedParts []minio.CompletePart, opts minio.ObjectOptions) (oi minio.ObjectInfo, err error) {
	client := l.Client
	bkt, err := client.Bucket(bucket)
	if err != nil {
		logger.LogIf(ctx, err)
		return oi, ossToObjectError(err, bucket, object)
	}

	// Error out if uploadedParts except last part sizing < 5MiB.
	// NOTE(timonwong): Actually, OSS wont't throw EntityTooSmall error, doing this check just for mint :(
	var partNumberMarker int
	lupr := oss.ListUploadedPartsResult{IsTruncated: true}
	for lupr.IsTruncated {
		lupr, err = ossListObjectParts(client, bucket, object, uploadID, partNumberMarker, ossMaxParts)
		if err != nil {
			logger.LogIf(ctx, err)
			return oi, ossToObjectError(err, bucket, object, uploadID)
		}

		uploadedParts := lupr.UploadedParts
		if !lupr.IsTruncated {
			if len(uploadedParts) < 1 {
				uploadedParts = nil
			} else {
				uploadedParts = uploadedParts[:len(uploadedParts)-1]
			}
		}

		for _, part := range uploadedParts {
			if part.Size < ossS3MinPartSize {
				logger.LogIf(ctx, minio.PartTooSmall{
					PartNumber: part.PartNumber,
					PartSize:   int64(part.Size),
					PartETag:   minio.ToS3ETag(part.ETag),
				})
				return oi, minio.PartTooSmall{
					PartNumber: part.PartNumber,
					PartSize:   int64(part.Size),
					PartETag:   minio.ToS3ETag(part.ETag),
				}
			}
		}

		partNumberMarker, _ = strconv.Atoi(lupr.NextPartNumberMarker)
	}

	imur := oss.InitiateMultipartUploadResult{
		Bucket:   bucket,
		Key:      object,
		UploadID: uploadID,
	}
	parts := make([]oss.UploadPart, len(uploadedParts))
	for i, up := range uploadedParts {
		parts[i] = oss.UploadPart{
			PartNumber: up.PartNumber,
			ETag:       strings.TrimSuffix(up.ETag, "-1"), // Trim "-1" suffix in ETag as PutObjectPart().
		}
	}

	_, err = bkt.CompleteMultipartUpload(imur, parts)
	if err != nil {
		logger.LogIf(ctx, err)
		return oi, ossToObjectError(err, bucket, object)
	}

	return l.GetObjectInfo(ctx, bucket, object, minio.ObjectOptions{})
}
143358
func newMultipart(url string, method string, body interface{}, files ...File) (*http.Request, error) {

	bb := &bytes.Buffer{}
	writer := multipart.NewWriter(bb)
	defer writer.Close()
	for _, f := range files {
		part, err := writer.CreateFormFile(f.ParamName, f.FileName)
		if err != nil {
			return nil, errors.WithStack(err)
		}
		_, err = io.Copy(part, f)
	}

	for k, v := range toURLValues(body) {
		for _, vv := range v {
			err := writer.WriteField(k, vv)
			if err != nil {
				return nil, errors.WithStack(err)
			}
		}
	}

	req, err := http.NewRequest(method, url, bb)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	return req, nil
}
555122
func IsMultipart(req *http.Request) bool {
	v := req.Header.Get("Content-Type")
	if v == "" {
		return false
	}
	d, _, err := mime.ParseMediaType(v)
	if err != nil || d != "multipart/form-data" {
		return false
	}
	return true
}
278264
func (bow *Browser) PostMultipart(u string, fields url.Values, files FileSet) error {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	for k, vs := range fields {
		for _, v := range vs {
			writer.WriteField(k, v)
		}
	}
	for k, file := range files {
		fw, err := writer.CreateFormFile(k, file.fileName)
		if err != nil {
			return err
		}
		if file.data != nil {
			_, err = io.Copy(fw, file.data)
			if err != nil {
				return err
			}
		}
	}
	err := writer.Close()
	if err != nil {
		return err

	}
	return bow.Post(u, writer.FormDataContentType(), body)
}
68267
func (m *Master) SubmitArgs(filename, mimeType string, file io.Reader, args url.Values) (fid string, size int64, err error) {
	data, contentType, err := makeFormData(filename, mimeType, file)
	if err != nil {
		return
	}

	u := url.URL{
		Scheme:   "http",
		Host:     m.Url,
		Path:     "/submit",
		RawQuery: args.Encode(),
	}

	resp, err := upload(u.String(), contentType, data)
	if err == nil {
		fid = resp.Fid
		size = resp.Size
	}

	return
}
490665
func (n Number) parseFormat(pattern string, includeDecimalDigits bool) *numberFormat {
	format := new(numberFormat)
	patterns := strings.Split(pattern, ";")

	matches := prefixSuffixRegex.FindAllStringSubmatch(patterns[0], -1)
	if len(matches) > 0 {
		if len(matches[0]) > 1 {
			format.positivePrefix = matches[0][1]
		}
		if len(matches[0]) > 2 {
			format.positiveSuffix = matches[0][2]
		}
	}

	// default values for negative prefix & suffix
	format.negativePrefix = string(n.Symbols.Negative) + string(format.positivePrefix)
	format.negativeSuffix = format.positiveSuffix

	// see if they are in the pattern
	if len(patterns) > 1 {
		matches = prefixSuffixRegex.FindAllStringSubmatch(patterns[1], -1)

		if len(matches) > 0 {
			if len(matches[0]) > 1 {
				format.negativePrefix = matches[0][1]
			}
			if len(matches[0]) > 2 {
				format.negativeSuffix = matches[0][2]
			}
		}
	}

	pat := patterns[0]

	if strings.Index(pat, "%") != -1 {
		format.multiplier = 100
	} else if strings.Index(pat, "‰") != -1 {
		format.multiplier = 1000
	} else {
		format.multiplier = 1
	}

	pos := strings.Index(pat, ".")

	if pos != -1 {
		pos2 := strings.LastIndex(pat, "0")
		if pos2 > pos {
			format.minDecimalDigits = pos2 - pos
		}

		pos3 := strings.LastIndex(pat, "#")
		if pos3 >= pos2 {
			format.maxDecimalDigits = pos3 - pos
		} else {
			format.maxDecimalDigits = format.minDecimalDigits
		}

		pat = pat[0:pos]
	}

	p := strings.Replace(pat, ",", "", -1)
	pos = strings.Index(p, "0")
	if pos != -1 {
		format.minIntegerDigits = strings.LastIndex(p, "0") - pos + 1
	}

	p = strings.Replace(pat, "#", "0", -1)
	pos = strings.LastIndex(pat, ",")
	if pos != -1 {
		format.groupSizeFinal = strings.LastIndex(p, "0") - pos
		pos2 := strings.LastIndex(p[0:pos], ",")
		if pos2 != -1 {
			format.groupSizeMain = pos - pos2 - 1
		} else {
			format.groupSizeMain = format.groupSizeFinal
		}
	}

	if !includeDecimalDigits {
		format.maxDecimalDigits = 0
		format.minDecimalDigits = 0
	}

	return format
}
1249362
func (a *S3Store) uploadPart(ctx context.Context, task *UploadTask, b job, previous *AttachmentInfo, previousParts map[int]s3.Part, multi s3.MultiInt, retCh chan s3.Part) (err error) {
	defer a.Trace(ctx, func() error { return err }, fmt.Sprintf("uploadPart(%d)", b.index))()

	// check to see if this part has already been uploaded.
	// for job `b` to be here, it has already passed local stash verification.
	if previous != nil {
		// check s3 previousParts for this block
		p, ok := previousParts[b.index]
		if ok && int(p.Size) == len(b.block) && p.ETag == b.etag() {
			a.Debug(ctx, "uploadPart: part %d already uploaded to s3", b.index)

			// part already uploaded, so put it in the retCh unless the context
			// has been canceled
			select {
			case retCh <- p:
			case <-ctx.Done():
				return ctx.Err()
			}

			// nothing else to do
			return nil
		}

		if p.Size > 0 {
			// only abort if the part size from s3 is > 0.
			a.Debug(ctx, "uploadPart: part %d s3 mismatch:  size %d != expected %d or etag %s != expected %s",
				b.index, p.Size, len(b.block), p.ETag, b.etag())
			return ErrAbortOnPartMismatch
		}

		// this part doesn't exist on s3, so it needs to be uploaded
		a.Debug(ctx, "uploadPart: part %d not uploaded to s3 by previous upload attempt", b.index)
	}

	// stash part info locally before attempting S3 put
	// doing this before attempting the S3 put is important
	// for security concerns.
	if err := a.stash.RecordPart(task.stashKey(), b.index, b.hash); err != nil {
		a.Debug(ctx, "uploadPart: StashRecordPart error: %s", err)
	}

	part, putErr := multi.PutPart(ctx, b.index, bytes.NewReader(b.block))
	if putErr != nil {
		return NewErrorWrapper(fmt.Sprintf("failed to put part %d", b.index), putErr)
	}

	// put the successfully uploaded part information in the retCh
	// unless the context has been canceled.
	select {
	case retCh <- part:
	case <-ctx.Done():
		a.Debug(ctx, "uploadPart: upload part %d, context canceled", b.index)
		return ctx.Err()
	}

	return nil
}
206331
func (c Core) CompleteMultipartUpload(bucket, object, uploadID string, parts []CompletePart) (string, error) {
	res, err := c.completeMultipartUpload(context.Background(), bucket, object, uploadID, completeMultipartUpload{
		Parts: parts,
	})
	return res.ETag, err
}
888613
func NewMultipartBuilder() MultipartBuilder {
	builder := MultipartBuilder{}
	var b bytes.Buffer
	builder.Buffer = &b
	builder.Writer = multipart.NewWriter(&b)
	return builder
}
276396
func (c *Client) UploadFile(name string, contents io.Reader, contentType string) (*ParseFile, error) {
	uri := "/1/files/"+name
	resp, err := c.do("POST", uri, contentType, contents)
	c.trace("UploadFile", uri, contentType)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result *ParseFile
	err = json.NewDecoder(resp.Body).Decode(&result)
	return result, err
}
270437
func (up *Uploader) uploadFilePermanode(ctx context.Context, sum string, fileRef blob.Ref, claimTime time.Time) error {
	if sum == "" {
		panic("invalid empty string for sum")
	}
	// Use a fixed time value for signing; not using modtime
	// so two identical files don't have different modtimes?
	// TODO(bradfitz): consider this more?
	permaNodeSigTime := time.Unix(0, 0)
	permaNode, err := up.UploadPlannedPermanode(ctx, sum, permaNodeSigTime)
	if err != nil {
		return fmt.Errorf("Error uploading planned permanode: %v", err)
	}
	handleResult("node-permanode", permaNode, nil)

	contentAttr := schema.NewSetAttributeClaim(permaNode.BlobRef, "camliContent", fileRef.String())
	contentAttr.SetClaimDate(claimTime)
	signer, err := up.Signer()
	if err != nil {
		return err
	}
	signed, err := contentAttr.SignAt(ctx, signer, claimTime)
	if err != nil {
		return fmt.Errorf("Failed to sign content claim: %v", err)
	}
	put, err := up.uploadString(ctx, signed)
	if err != nil {
		return fmt.Errorf("Error uploading permanode's attribute: %v", err)
	}

	handleResult("node-permanode-contentattr", put, nil)
	if tags := up.fileOpts.tags(); len(tags) > 0 {
		errch := make(chan error)
		for _, tag := range tags {
			go func(tag string) {
				m := schema.NewAddAttributeClaim(permaNode.BlobRef, "tag", tag)
				m.SetClaimDate(claimTime)
				signed, err := m.SignAt(ctx, signer, claimTime)
				if err != nil {
					errch <- fmt.Errorf("Failed to sign tag claim: %v", err)
					return
				}
				put, err := up.uploadString(ctx, signed)
				if err != nil {
					errch <- fmt.Errorf("Error uploading permanode's tag attribute %v: %v", tag, err)
					return
				}
				handleResult("node-permanode-tag", put, nil)
				errch <- nil
			}(tag)
		}

		for range tags {
			if e := <-errch; e != nil && err == nil {
				err = e
			}
		}
		if err != nil {
			return err
		}
	}
	return nil
}
1200052
func (s *Bucket) CompleteMultipartUpload(objectKey string, input *CompleteMultipartUploadInput) (*CompleteMultipartUploadOutput, error) {
	r, x, err := s.CompleteMultipartUploadRequest(objectKey, input)

	if err != nil {
		return x, err
	}

	err = r.Send()
	if err != nil {
		return nil, err
	}

	requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
	x.RequestID = &requestID

	return x, err
}
841207
func (mr *MockJobRendererMockRecorder) RenderAndUploadFrom(arg0, arg1, arg2 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RenderAndUploadFrom", reflect.TypeOf((*MockJobRenderer)(nil).RenderAndUploadFrom), arg0, arg1, arg2)
}
970063
func (e *Entity) MultipartReader() MultipartReader {
	if !strings.HasPrefix(e.mediaType, "multipart/") {
		return nil
	}
	if mb, ok := e.Body.(*multipartBody); ok {
		return mb
	}
	return &multipartReader{multipart.NewReader(e.Body, e.mediaParams["boundary"])}
}
406361
func ParseFileMode(s string) (FileMode, error) {
	var fm FileMode
	if err := fm.UnmarshalText([]byte(s)); err != nil {
		return 0, err
	}
	return fm, nil
}