Simple upload and return quickkey

        Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES

        upload_info -- UploadInfo object
        check_result -- ignored
425518
def _upload_simple(self, upload_info, _=None):
        

        upload_result = self._api.upload_simple(
            upload_info.fd,
            upload_info.name,
            folder_key=upload_info.folder_key,
            filedrop_key=upload_info.filedrop_key,
            path=upload_info.path,
            file_size=upload_info.size,
            file_hash=upload_info.hash_info.file,
            action_on_duplicate=upload_info.action_on_duplicate)

        logger.debug("upload_result: %s", upload_result)

        upload_key = upload_result['doupload']['key']

        return self._poll_upload(upload_key, 'upload/simple')
1077407
function _ruleCheckMaxFileSize($elementValue, $maxSize)
    {
        if (!empty($elementValue['error']) && 
            (UPLOAD_ERR_FORM_SIZE == $elementValue['error'] || UPLOAD_ERR_INI_SIZE == $elementValue['error'])) {
            return false;
        }
        if (!HTML_QuickForm_file::_ruleIsUploadedFile($elementValue)) {
            return true;
        }
        return ($maxSize >= @filesize($elementValue['tmp_name']));
    }
522455
private boolean readLength(SelectionKey k) throws IOException {
        // Read the length, now get the buffer
        int len = lenBuffer.getInt();
        if (!initialized && checkFourLetterWord(k, len)) {
            return false;
        }
        if (len < 0 || len > BinaryInputArchive.maxBuffer) {
            throw new IOException("Len error " + len);
        }
        if (zk == null) {
            throw new IOException("ZooKeeperServer not running");
        }
        incomingBuffer = ByteBuffer.allocate(len);
        return true;
    }
495629
def _attempt_resumable_upload(self, key, fp, file_length, headers, cb,
                                  num_cb):
        
        (server_start, server_end) = self.SERVER_HAS_NOTHING
        conn = key.bucket.connection
        if self.tracker_uri:
            # Try to resume existing resumable upload.
            try:
                (server_start, server_end) = (
                    self._query_server_pos(conn, file_length))
                self.server_has_bytes = server_start
                key=key
                if conn.debug >= 1:
                    print 'Resuming transfer.'
            except ResumableUploadException, e:
                if conn.debug >= 1:
                    print 'Unable to resume transfer (%s).' % e.message
                self._start_new_resumable_upload(key, headers)
        else:
            self._start_new_resumable_upload(key, headers)

        # upload_start_point allows the code that instantiated the
        # ResumableUploadHandler to find out the point from which it started
        # uploading (e.g., so it can correctly compute throughput).
        if self.upload_start_point is None:
            self.upload_start_point = server_end

        if server_end == file_length:
            # Boundary condition: complete file was already uploaded (e.g.,
            # user interrupted a previous upload attempt after the upload
            # completed but before the gsutil tracker file was deleted). Set
            # total_bytes_uploaded to server_end so we'll attempt to upload
            # no more bytes but will still make final HTTP request and get
            # back the response (which contains the etag we need to compare
            # at the end).
            total_bytes_uploaded = server_end
        else:
            total_bytes_uploaded = server_end + 1
        fp.seek(total_bytes_uploaded)
        conn = key.bucket.connection

        # Get a new HTTP connection (vs conn.get_http_connection(), which reuses
        # pool connections) because httplib requires a new HTTP connection per
        # transaction. (Without this, calling http_conn.getresponse() would get
        # "ResponseNotReady".)
        http_conn = conn.new_http_connection(self.tracker_uri_host,
                                             conn.is_secure)
        http_conn.set_debuglevel(conn.debug)

        # Make sure to close http_conn at end so if a local file read
        # failure occurs partway through server will terminate current upload
        # and can report that progress on next attempt.
        try:
            return self._upload_file_bytes(conn, http_conn, fp, file_length,
                                           total_bytes_uploaded, cb, num_cb)
        except (ResumableUploadException, socket.error):
            resp = self._query_server_state(conn, file_length)
            if resp.status == 400:
                raise ResumableUploadException('Got 400 response from server '
                    'state query after failed resumable upload attempt. This '
                    'can happen for various reasons, including specifying an '
                    'invalid request (e.g., an invalid canned ACL) or if the '
                    'file size changed between upload attempts',
                    ResumableTransferDisposition.ABORT)
            else:
                raise
        finally:
            http_conn.close()
666116
def upload(self, release, filename, content_type=None):
        
        release = self.as_id(release)
        name = os.path.basename(filename)
        if not content_type:
            content_type, _ = mimetypes.guess_type(name)
        if not content_type:
            raise ValueError('content_type not known')
        inputs = {'name': name}
        url = '%s%s/%s/assets' % (self.uploads_url,
                                  urlsplit(self.api_url).path,
                                  release)
        info = os.stat(filename)
        size = info[stat.ST_SIZE]
        response = self.http.post(
            url, data=stream_upload(filename), auth=self.auth,
            params=inputs,
            headers={'content-type': content_type,
                     'content-length': str(size)})
        response.raise_for_status()
        return response.json()
252247
def recent_uploads(limit = nil, offset = nil, page = nil)
      args = {
        "limit" => limit,
        "offset" => offset,
        "page" => page
      }.reject { |_, v| v.nil? }
      if args.size > 0
        search = "?"
        args.each { |k, v| search += "#{k}=#{v}&" }
      else
        search = ""
      end

      result = access_token.get("#{API_BASE}#{API_PATH}recent_uploads#{search}")
      raise ServiceError.new(result.code, result.body) unless result.code == "200"

      JSON.parse(result.body)["recent_uploads"].map { |icon| Icon.new(icon) }
    end
1234651
def upload_check(self, filename=None, folder_key=None, filedrop_key=None,
                     size=None, hash_=None, path=None, resumable=None):
        
        return self.request('upload/check', QueryParams({
            'filename': filename,
            'folder_key': folder_key,
            'filedrop_key': filedrop_key,
            'size': size,
            'hash': hash_,
            'path': path,
            'resumable': resumable
        }))
472430
def _poll_upload(self, upload_key, action):
        

        if len(upload_key) != UPLOAD_KEY_LENGTH:
            # not a regular 11-char-long upload key
            # There is no API to poll filedrop uploads
            return UploadResult(
                action=action,
                quickkey=None,
                hash_=None,
                filename=None,
                size=None,
                created=None,
                revision=None
            )

        quick_key = None
        while quick_key is None:
            poll_result = self._api.upload_poll(upload_key)
            doupload = poll_result['doupload']

            logger.debug("poll(%s): status=%d, description=%s, filename=%s,"
                         " result=%d",
                         upload_key, int(doupload['status']),
                         doupload['description'], doupload['filename'],
                         int(doupload['result']))

            if int(doupload['result']) != 0:
                break

            if doupload['fileerror'] != '':
                # TODO: we may have to handle this a bit more dramatically
                logger.warning("poll(%s): fileerror=%d", upload_key,
                               int(doupload['fileerror']))
                break

            if int(doupload['status']) == STATUS_NO_MORE_REQUESTS:
                quick_key = doupload['quickkey']
            elif int(doupload['status']) == STATUS_UPLOAD_IN_PROGRESS:
                # BUG: http://forum.mediafiredev.com/showthread.php?588
                raise RetriableUploadError(
                    "Invalid state transition ({})".format(
                        doupload['description']
                    )
                )
            else:
                time.sleep(UPLOAD_POLL_INTERVAL)

        return UploadResult(
            action=action,
            quickkey=doupload['quickkey'],
            hash_=doupload['hash'],
            filename=doupload['filename'],
            size=doupload['size'],
            created=doupload['created'],
            revision=doupload['revision']
        )
1277138
def upload(self, payload=None, content_type=None):
        
        # platform - prefer the value passed in to func over config
        payload = payload or self.config.payload
        content_type = content_type or self.config.content_type

        if payload is None:
            raise ValueError('Specify a file to upload.')

        if not os.path.exists(payload):
            raise IOError('Cannot upload %s: File does not exist.' % payload)

        upload_results = client.upload(
            self.config, self.connection, payload, content_type)

        # return api response
        return upload_results
1273443
function (upload) {

						if (!upload || !upload.path || !upload.name || !upload.size) {
							LOG.error('upload object incomplete:', l_name);
							return;
						}

						// record basic file info
						var arr = upload.path.split('/');
						var upload_name = arr[arr.length-1];
						var filename = (preserve_name ? upload.name : upload_name); 
						LOG.warn("The file " + upload.name + " was uploaded as: " + filename + ". size: " + upload.size, l_name);
						uploaded.push({name: filename, size: upload.size, type: upload.type});						

						// check if we might need to re-name
						// default is to rename (preserve upload file names)
						if (preserve_name === false) {
							return;
						}

						var new_name = SR.path.resolve(form.uploadDir, upload.name);
						SR.fs.rename(upload.path, new_name, function (err) {
							if (err) {
								return LOG.error('rename fail: ' + new_name, l_name);
							}
							LOG.warn("File " + upload_name + " renamed as: " + upload.name + " . size: " + upload.size, l_name);							
						});
					}
610964
def _upload_in_splits( self, destination_folder_id, source_path, preflight_check, verbose = True, chunked_upload_threads = 5 ):
        '''
        
        '''
        file_size = os.stat(source_path).st_size
        split_size = BOX_MAX_FILE_SIZE

        # Make sure that the last split piece is still big enough for a chunked upload
        while file_size % split_size < BOX_MIN_CHUNK_UPLOAD_SIZE:
            split_size -= 1000
            if split_size < BOX_MIN_CHUNK_UPLOAD_SIZE:
                raise Exception('Lazy programming error')

        split_start_byte = 0
        part_count = 0
        uploaded_file_ids = []
        while split_start_byte < file_size:
            dest_file_name = '{0}.part{1}'.format( os.path.basename(source_path), part_count)
            prev_uploaded_file_ids = self.find_file( destination_folder_id, dest_file_name )
            if len( prev_uploaded_file_ids ) == 1:
                if verbose:
                    print ( '\nSkipping upload of split {0} of {1}; already exists'.format( part_count + 1, math.ceil(file_size / split_size) ) )
                uploaded_file_ids.extend( prev_uploaded_file_ids )
            else:
                if verbose:
                    print ( '\nUploading split {0} of {1}'.format( part_count + 1, math.ceil(file_size / split_size) ) )
                uploaded_file_ids.append( self._chunked_upload(
                    destination_folder_id, source_path,
                    dest_file_name = dest_file_name,
                    split_start_byte = split_start_byte,
                    file_size = min(split_size, file_size - split_start_byte), # Take the min of file_size - split_start_byte so that the last part of a split doesn't read into the next split
                    preflight_check = preflight_check,
                    verbose = verbose,
                    upload_threads = chunked_upload_threads,
                ) )
            part_count += 1
            split_start_byte += split_size

        return uploaded_file_ids
613353
def validate_partial_uploads!(part_uids)
      input = Queue.new
      part_uids.each { |part_uid| input << part_uid }
      input.close

      results = Queue.new

      thread_count   = storage.concurrency[:concatenation] if storage.respond_to?(:concurrency)
      thread_count ||= 10

      threads = thread_count.times.map do
        Thread.new do
          begin
            loop do
              part_uid = input.pop or break
              part_info = storage.read_info(part_uid)
              results << Tus::Info.new(part_info)
            end
            nil
          rescue => error
            input.clear
            error
          end
        end
      end

      errors = threads.map(&:value).compact

      if errors.any? { |error| error.is_a?(Tus::NotFound) }
        error!(400, "One or more partial uploads were not found")
      elsif errors.any?
        fail errors.first
      end

      part_infos = Array.new(results.size) { results.pop } # convert Queue into an Array

      unless part_infos.all?(&:partial?)
        error!(400, "One or more uploads were not partial")
      end

      if max_size && part_infos.map(&:length).inject(0, :+) > max_size
        error!(400, "The sum of partial upload lengths exceed Tus-Max-Size")
      end
    end
764838
def UploadType(cls, file_path):
        
        if not os.path.isabs(file_path):
            return False
        
        if os.path.isfile(file_path):
            cls.SendKeys(file_path)
        else:            
            return False
65324
function upload() {
      stop_loop = false;

      if (!files) {
        opts.error(errors[0]);
        return false;
      }

      if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
        for(var fileIndex = files.length;fileIndex--;) {
          if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
            opts.error(errors[3], files[fileIndex]);
            return false;
          }
        }
      }

      var filesDone = 0,
          filesRejected = 0;

      if (files_count > opts.maxfiles && opts.queuefiles === 0) {
        opts.error(errors[1]);
        return false;
      }

      // Define queues to manage upload process
      var workQueue = [];
      var processingQueue = [];
      var doneQueue = [];

      // Add everything to the workQueue
      for (var i = 0; i < files_count; i++) {
        workQueue.push(i);
      }

      // Helper function to enable pause of processing to wait
      // for in process queue to complete
      var pause = function(timeout) {
        setTimeout(process, timeout);
        return;
      };

      // Process an upload, recursive
      var process = function() {

        var fileIndex;

        if (stop_loop) {
          return false;
        }

        // Check to see if are in queue mode
        if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
          return pause(opts.queuewait);
        } else {
          // Take first thing off work queue
          fileIndex = workQueue[0];
          workQueue.splice(0, 1);

          // Add to processing queue
          processingQueue.push(fileIndex);
        }

        try {
          if (beforeEach(files[fileIndex]) !== false) {
            if (fileIndex === files_count) {
              return;
            }
            var reader = new FileReader(),
                max_file_size = 1048576 * opts.maxfilesize;

            reader.index = fileIndex;
            if (files[fileIndex].size > max_file_size) {
              opts.error(errors[2], files[fileIndex], fileIndex);
              // Remove from queue
              processingQueue.forEach(function(value, key) {
                if (value === fileIndex) {
                  processingQueue.splice(key, 1);
                }
              });
              filesRejected++;
              return true;
            }

            reader.onloadend = !opts.beforeSend ? send : function (e) {
              opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
            };

            reader.readAsBinaryString(files[fileIndex]);

          } else {
            filesRejected++;
          }
        } catch (err) {
          // Remove from queue
          processingQueue.forEach(function(value, key) {
            if (value === fileIndex) {
              processingQueue.splice(key, 1);
            }
          });
          opts.error(errors[0]);
          return false;
        }

        // If we still have work to do,
        if (workQueue.length > 0) {
          process();
        }
      };

      var send = function(e) {

        var fileIndex = ((typeof(e.srcElement) === "undefined") ? e.target : e.srcElement).index;

        // Sometimes the index is not attached to the
        // event object. Find it by size. Hack for sure.
        if (e.target.index === undefined) {
          e.target.index = getIndexBySize(e.total);
        }

        var xhr = new XMLHttpRequest(),
            upload = xhr.upload,
            file = files[e.target.index],
            index = e.target.index,
            start_time = new Date().getTime(),
            boundary = '------multipartformboundary' + (new Date()).getTime(),
            global_progress_index = global_progress.length,
            builder,
            newName = rename(file.name),
            mime = file.type;

        if (typeof newName === "string") {
          builder = getBuilder(newName, e.target.result, mime, boundary);
        } else {
          builder = getBuilder(file.name, e.target.result, mime, boundary);
        }

        upload.index = index;
        upload.file = file;
        upload.downloadStartTime = start_time;
        upload.currentStart = start_time;
        upload.currentProgress = 0;
        upload.global_progress_index = global_progress_index;
        upload.startData = 0;
        upload.addEventListener("progress", progress, false);

        xhr.open("POST", opts.url, true);
        xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);

        // Add headers
        $.each(opts.headers, function(k, v) {
          xhr.setRequestHeader(k, v);
        });

        xhr.sendAsBinary(builder);

        global_progress[global_progress_index] = 0;
        globalProgress();

        opts.uploadStarted(index, file, files_count);

        xhr.onload = function() {
            var serverResponse = null;

            if (xhr.responseText) {
              try {
                serverResponse = jQuery.parseJSON(xhr.responseText);
              }
              catch (e) {
                serverResponse = xhr.responseText;
              }
            }

            var now = new Date().getTime(),
                timeDiff = now - start_time,
                result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
            filesDone++;

            // Remove from processing queue
            processingQueue.forEach(function(value, key) {
              if (value === fileIndex) {
                processingQueue.splice(key, 1);
              }
            });

            // Add to donequeue
            doneQueue.push(fileIndex);

            // Make sure the global progress is updated
            global_progress[global_progress_index] = 100;
            globalProgress();

            if (filesDone === (files_count - filesRejected)) {
              afterAll();
            }
            if (result === false) {
              stop_loop = true;
            }
          

          // Pass any errors to the error option
          if (xhr.status < 200 && xhr.status > 299) {
            opts.error(xhr.statusText);
          }
        };
      };

      // Initiate the processing loop
      process();
    }
1235827
def _upload_file_bytes(self, conn, http_conn, fp, file_length,
                           total_bytes_uploaded, cb, num_cb):
        
        buf = fp.read(self.BUFFER_SIZE)
        if cb:
            if num_cb > 2:
                cb_count = file_length / self.BUFFER_SIZE / (num_cb-2)
            elif num_cb < 0:
                cb_count = -1
            else:
                cb_count = 0
            i = 0
            cb(total_bytes_uploaded, file_length)

        # Build resumable upload headers for the transfer. Don't send a
        # Content-Range header if the file is 0 bytes long, because the
        # resumable upload protocol uses an *inclusive* end-range (so, sending
        # 'bytes 0-0/1' would actually mean you're sending a 1-byte file).
        put_headers = {}
        if file_length:
            range_header = self._build_content_range_header(
                '%d-%d' % (total_bytes_uploaded, file_length - 1),
                file_length)
            put_headers['Content-Range'] = range_header
        # Set Content-Length to the total bytes we'll send with this PUT.
        put_headers['Content-Length'] = str(file_length - total_bytes_uploaded)
        http_request = AWSAuthConnection.build_base_http_request(
            conn, 'PUT', path=self.tracker_uri_path, auth_path=None,
            headers=put_headers, host=self.tracker_uri_host)
        http_conn.putrequest('PUT', http_request.path)
        for k in put_headers:
            http_conn.putheader(k, put_headers[k])
        http_conn.endheaders()

        # Turn off debug on http connection so upload content isn't included
        # in debug stream.
        http_conn.set_debuglevel(0)
        while buf:
            http_conn.send(buf)
            total_bytes_uploaded += len(buf)
            if cb:
                i += 1
                if i == cb_count or cb_count == -1:
                    cb(total_bytes_uploaded, file_length)
                    i = 0
            buf = fp.read(self.BUFFER_SIZE)
        if cb:
            cb(total_bytes_uploaded, file_length)
        if total_bytes_uploaded != file_length:
            # Abort (and delete the tracker file) so if the user retries
            # they'll start a new resumable upload rather than potentially
            # attempting to pick back up later where we left off.
            raise ResumableUploadException(
                'File changed during upload: EOF at %d bytes of %d byte file.' %
                (total_bytes_uploaded, file_length),
                ResumableTransferDisposition.ABORT)
        resp = http_conn.getresponse()
        body = resp.read()
        # Restore http connection debug level.
        http_conn.set_debuglevel(conn.debug)

        if resp.status == 200:
            return resp.getheader('etag')  # Success
        # Retry timeout (408) and status 500 and 503 errors after a delay.
        elif resp.status in [408, 500, 503]:
            disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY
        else:
            # Catch all for any other error codes.
            disposition = ResumableTransferDisposition.ABORT
        raise ResumableUploadException('Got response code %d while attempting '
                                       'upload (%s)' %
                                       (resp.status, resp.reason), disposition)
413225
function(params, callback) {
                var fileName,
                    fileType,
                    fileSize,
                    fileExtension,
                    uploadUniqueId,
                    uploadThreadId;

                fileName = params.image.name;
                fileType = params.image.type;
                fileSize = params.image.size;
                fileExtension = params.image.name.split('.')
                    .pop();

                if (imageMimeTypes.indexOf(fileType) > 0 || imageExtentions.indexOf(fileExtension) > 0) {
                    uploadImageData = {};

                    if (params) {
                        if (typeof params.image !== 'undefined') {
                            uploadImageData.image = params.image;
                            uploadImageData.file = params.image;
                        }

                        if (typeof params.fileName == 'string') {
                            uploadImageData.fileName = params.fileName;
                        }
                        else {
                            uploadImageData.fileName = Utility.generateUUID() + '.' + fileExtension;
                        }

                        uploadImageData.fileSize = fileSize;

                        if (parseInt(params.threadId) > 0) {
                            uploadThreadId = params.threadId;
                            uploadImageData.threadId = params.threadId;
                        }
                        else {
                            uploadThreadId = 0;
                            uploadImageData.threadId = 0;
                        }

                        if (typeof params.uniqueId == 'string') {
                            uploadUniqueId = params.uniqueId;
                            uploadImageData.uniqueId = params.uniqueId;
                        }
                        else {
                            uploadUniqueId = Utility.generateUUID();
                            uploadImageData.uniqueId = uploadUniqueId;
                        }

                        if (typeof params.originalFileName == 'string') {
                            uploadImageData.originalFileName = params.originalFileName;
                        }
                        else {
                            uploadImageData.originalFileName = fileName;
                        }

                        if (parseInt(params.xC) > 0) {
                            uploadImageData.xC = params.xC;
                        }

                        if (parseInt(params.yC) > 0) {
                            uploadImageData.yC = params.yC;
                        }

                        if (parseInt(params.hC) > 0) {
                            uploadImageData.hC = params.hC;
                        }

                        if (parseInt(params.wC) > 0) {
                            uploadImageData.wC = params.wC;
                        }
                    }

                    httpRequest({
                        url: SERVICE_ADDRESSES.FILESERVER_ADDRESS + SERVICES_PATH.UPLOAD_IMAGE,
                        method: 'POST',
                        headers: {
                            '_token_': token,
                            '_token_issuer_': 1
                        },
                        data: uploadImageData,
                        uniqueId: uploadUniqueId
                    }, function(result) {
                        if (!result.hasError) {
                            try {
                                var response = (typeof result.result.responseText == 'string')
                                    ? JSON.parse(result.result.responseText)
                                    : result.result.responseText;
                                if (typeof response.hasError !== 'undefined' && !response.hasError) {
                                    callback({
                                        hasError: response.hasError,
                                        result: response.result
                                    });
                                }
                                else {
                                    callback({
                                        hasError: true,
                                        errorCode: response.errorCode,
                                        errorMessage: response.message
                                    });
                                }
                            }
                            catch (e) {
                                callback({
                                    hasError: true,
                                    errorCode: 6300,
                                    errorMessage: CHAT_ERRORS[6300]
                                });
                            }
                        }
                        else {
                            callback({
                                hasError: true,
                                errorCode: result.errorCode,
                                errorMessage: result.errorMessage
                            });
                        }
                    });

                    return {
                        uniqueId: uploadUniqueId,
                        threadId: uploadThreadId,
                        participant: userInfo,
                        content: {
                            caption: params.content,
                            file: {
                                uniqueId: uploadUniqueId,
                                fileName: fileName,
                                fileSize: fileSize,
                                fileObject: params.file
                            }
                        }
                    };
                }
                else {
                    callback({
                        hasError: true,
                        errorCode: 6301,
                        errorMessage: CHAT_ERRORS[6301]
                    });
                }
            }
824598
def _start_new_resumable_upload(self, key, headers=None):
        
        conn = key.bucket.connection
        if conn.debug >= 1:
            print 'Starting new resumable upload.'
        self.server_has_bytes = 0

        # Start a new resumable upload by sending a POST request with an
        # empty body and the "X-Goog-Resumable: start" header. Include any
        # caller-provided headers (e.g., Content-Type) EXCEPT Content-Length
        # (and raise an exception if they tried to pass one, since it's
        # a semantic error to specify it at this point, and if we were to
        # include one now it would cause the server to expect that many
        # bytes; the POST doesn't include the actual file bytes  We set
        # the Content-Length in the subsequent PUT, based on the uploaded
        # file size.
        post_headers = {}
        for k in headers:
            if k.lower() == 'content-length':
                raise ResumableUploadException(
                    'Attempt to specify Content-Length header (disallowed)',
                    ResumableTransferDisposition.ABORT)
            post_headers[k] = headers[k]
        post_headers[conn.provider.resumable_upload_header] = 'start'

        resp = conn.make_request(
            'POST', key.bucket.name, key.name, post_headers)
        # Get tracker URI from response 'Location' header.
        body = resp.read()

        # Check for various status conditions.
        if resp.status in [500, 503]:
            # Retry status 500 and 503 errors after a delay.
            raise ResumableUploadException(
                'Got status %d from attempt to start resumable upload. '
                'Will wait/retry' % resp.status,
                ResumableTransferDisposition.WAIT_BEFORE_RETRY)
        elif resp.status != 200 and resp.status != 201:
            raise ResumableUploadException(
                'Got status %d from attempt to start resumable upload. '
                'Aborting' % resp.status,
                ResumableTransferDisposition.ABORT)

        # Else we got 200 or 201 response code, indicating the resumable
        # upload was created.
        tracker_uri = resp.getheader('Location')
        if not tracker_uri:
            raise ResumableUploadException(
                'No resumable tracker URI found in resumable initiation '
                'POST response (%s)' % body,
                ResumableTransferDisposition.WAIT_BEFORE_RETRY)
        self._set_tracker_uri(tracker_uri)
        self._save_tracker_uri_to_file()