under the temporary multipart upload directory are combined into the final object.
763159
private Response completeMultipartUpload(final String bucket, final String object,
      final long uploadId) {
    return S3RestUtils.call(bucket, new S3RestUtils.RestCallable<CompleteMultipartUploadResult>() {
      @Override
      public CompleteMultipartUploadResult call() throws S3Exception {
        String bucketPath = parseBucketPath(AlluxioURI.SEPARATOR + bucket);
        checkBucketIsAlluxioDirectory(bucketPath);
        String objectPath = bucketPath + AlluxioURI.SEPARATOR + object;
        AlluxioURI multipartTemporaryDir =
            new AlluxioURI(S3RestUtils.getMultipartTemporaryDirForObject(bucketPath, object));
        checkUploadId(multipartTemporaryDir, uploadId);

        try {
          List<URIStatus> parts = mFileSystem.listStatus(multipartTemporaryDir);
          Collections.sort(parts, new URIStatusNameComparator());

          CreateFilePOptions options = CreateFilePOptions.newBuilder().setRecursive(true)
              .setWriteType(getS3WriteType()).build();
          FileOutStream os = mFileSystem.createFile(new AlluxioURI(objectPath), options);
          MessageDigest md5 = MessageDigest.getInstance("MD5");
          DigestOutputStream digestOutputStream = new DigestOutputStream(os, md5);

          try {
            for (URIStatus part : parts) {
              try (FileInStream is = mFileSystem.openFile(new AlluxioURI(part.getPath()))) {
                ByteStreams.copy(is, digestOutputStream);
              }
            }
          } finally {
            digestOutputStream.close();
          }

          mFileSystem.delete(multipartTemporaryDir,
              DeletePOptions.newBuilder().setRecursive(true).build());

          String entityTag = Hex.encodeHexString(md5.digest());
          return new CompleteMultipartUploadResult(objectPath, bucket, object, entityTag);
        } catch (Exception e) {
          throw toObjectS3Exception(e, objectPath);
        }
      }
    });
  }
1317465
def store_uploaded_file(title, uploaded_file):
    
    upload_dir_path = '%s/static/taskManager/uploads' % (
        os.path.dirname(os.path.realpath(__file__)))
    if not os.path.exists(upload_dir_path):
        os.makedirs(upload_dir_path)

    # A1: Injection (shell)
    # Let's avoid the file corruption race condition!
    os.system(
        "mv " +
        uploaded_file.temporary_file_path() +
        " " +
        "%s/%s" %
        (upload_dir_path,
         title))

    return '/static/taskManager/uploads/%s' % (title)
409891
@POST
	@Path("/upload")
	@Consumes("multipart/form-data")
	@AllowSecurityBypassedByToken
	public void upload(MultipartFormDataInput input) throws IOException {
		Map<String, List<InputPart>> formDataMap = input.getFormDataMap();
		List<InputPart> inputParts = formDataMap.get("uploadedFile");

		for (InputPart inputPart : inputParts) {
			String fileName = getFileName(inputPart.getHeaders());
			InputStream inputStream = inputPart.getBody(InputStream.class, null);
			File file = File.createTempFile(HomeWS.class.getSimpleName(), ".tmp");
			IOUtils.copy(inputStream, new FileOutputStream(file));
			uploadedFiles.put(fileName, file);
		}
	}
980109
private void execUpload(UploadPartRequest request) {
    File file = request.getFile();
    ListenableFuture<PartETag> futureTag =
        mExecutor.submit((Callable) () -> {
          PartETag partETag;
          AmazonClientException lastException;
          try {
            do {
              try {
                partETag = mClient.uploadPart(request).getPartETag();
                return partETag;
              } catch (AmazonClientException e) {
                lastException = e;
              }
            } while (mRetryPolicy.attempt());
          } finally {
            // Delete the uploaded or failed to upload file
            if (!file.delete()) {
              LOG.error("Failed to delete temporary file @ {}", file.getPath());
            }
          }
          throw new IOException("Fail to upload part " + request.getPartNumber()
              + " to " + request.getKey(), lastException);
        });
    mTagFutures.add(futureTag);
    LOG.debug("Submit upload part request. key={}, partNum={}, file={}, fileSize={}, lastPart={}.",
        mKey, request.getPartNumber(), file.getPath(), file.length(), request.isLastPart());
  }
1133674
protected function moveUploadedFiles()
    {
        $i = 0;
        if (is_array($this->move_uploaded_queue)) {
            foreach ($this->move_uploaded_queue as $key => $queue_item) {
                if (is_array($queue_item) && isset($queue_item['name']) && isset($queue_item['tmp_name']) && isset($queue_item['new_name'])) {
                    $destination_name = $queue_item['new_name'];

                    if ($this->overwrite === false) {
                        // verify file exists and set new name.
                        $destination_name = $this->renameDuplicateFile($destination_name);
                    }

                    $move_result = move_uploaded_file($queue_item['tmp_name'], $this->move_uploaded_to.DIRECTORY_SEPARATOR.$destination_name);
                    if ($move_result === true) {
                        // move uploaded file success. add status and some data to array.
                        $this->move_uploaded_queue[$key] = array_merge(
                            $this->move_uploaded_queue[$key], 
                            array(
                                'new_name' => $destination_name,
                                'move_uploaded_status' => 'success',
                                'move_uploaded_to' => $this->move_uploaded_to.DIRECTORY_SEPARATOR.$destination_name,
                            )
                        );
                        $i++;
                    } else {
                        $this->setErrorMessage(
                            sprintf(static::__('Unable to move uploaded file. (%s =&gt; %s)'), $queue_item['name'], $this->move_uploaded_to . DIRECTORY_SEPARATOR . $destination_name),
                            'RDU_MOVE_UPLOADED_FAILED',
                            $queue_item['name'] . '=&gt; ' . $this->move_uploaded_to . DIRECTORY_SEPARATOR . $destination_name
                        );
                    }

                    unset($destination_name, $move_result);
                }
            }// endforeach;
            unset($key, $queue_item);
        }

        if ($i == count($this->move_uploaded_queue) && $i > 0) {
            return true;
        } else {
            return false;
        }
    }
868261
function ($placeholder, files, that) {
			var acceptedTypes = {
				'image/png': true,
				'image/jpeg': true,
				'image/gif': true
			};

			for (var i = 0; i < files.length; i++) {
				var file = files[i];

				if (acceptedTypes[file.type] === true) {
					$placeholder.append('<progress class="progress" min="0" max="100" value="0">0</progress>');

					that.uploadFile($placeholder, file, that);
				}
			}
		}
999314
def with_temporary_files(file_contents='', dest_extension = '', source_extension = '', message=nil)

      #File mode for all of the created temporary files.
      #Create the files, and allow read/write, but do not lock for exclusive access.
      file_mode = File::CREAT | File::RDWR

      #Create a new file which contains the provided file content.
      #Used to pass arbitrary data into an external tool.
      Tempfile.open(['core_prev', source_extension], :mode => file_mode) do |source_file|

        #Fill the source file with the provided file contents...
        source_file.write(file_contents)
        source_file.flush

        #Create a new file which will store the resultant file content.
        Tempfile.open(['core_next', dest_extension], :mode => file_mode) do |destination_file|

          #Yield the file's paths the provided block.
          raise CommandFailedError, message unless yield [destination_file.path, source_file.path]

          #And return the content of the destination file.
          return File::read(destination_file)

        end

      end
    end
867793
def _finalize_upload(self, sd):
        # type: (SyncCopy, blobxfer.models.synccopy.Descriptor) -> None
        
        metadata = sd.src_entity.raw_metadata
        if blobxfer.util.is_not_empty(sd.src_entity.md5):
            digest = sd.src_entity.md5
        else:
            digest = None
        if sd.requires_put_block_list:
            # put block list for non one-shot block blobs
            self._finalize_block_blob(sd, metadata, digest)
        elif sd.remote_is_page_blob or sd.remote_is_append_blob:
            # append and page blob finalization
            self._finalize_nonblock_blob(sd, metadata, digest)
        elif sd.remote_is_file:
            # azure file finalization
            self._finalize_azure_file(sd, metadata, digest)
        # set access tier
        if sd.requires_access_tier_set:
            blobxfer.operations.azure.blob.block.set_blob_access_tier(
                sd.dst_entity)
605139
private void initMultiPartUpload() throws IOException {
    // Generate the object metadata by setting server side encryption, md5 checksum,
    // and encoding as octet stream since no assumptions are made about the file type
    ObjectMetadata meta = new ObjectMetadata();
    if (mSseEnabled) {
      meta.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
    }
    if (mHash != null) {
      meta.setContentMD5(Base64.encodeAsString(mHash.digest()));
    }
    meta.setContentType(Mimetypes.MIMETYPE_OCTET_STREAM);

    AmazonClientException lastException;
    InitiateMultipartUploadRequest initRequest =
        new InitiateMultipartUploadRequest(mBucketName, mKey).withObjectMetadata(meta);
    do {
      try {
        mUploadId = mClient.initiateMultipartUpload(initRequest).getUploadId();
        return;
      } catch (AmazonClientException e) {
        lastException = e;
      }
    } while (mRetryPolicy.attempt());
    // This point is only reached if the operation failed more
    // than the allowed retry count
    throw new IOException("Unable to init multipart upload to " + mKey, lastException);
  }
781308
def multipart_content(*files):
    
    outer = MIMEMultipart()
    for fname in files:
        mtype = get_type(fname)
        maintype, subtype = mtype.split('/', 1)
        with open(fname) as f:
            msg = MIMEText(f.read(), _subtype=subtype)
        msg.add_header('Content-Disposition', 'attachment', 
                       filename=os.path.basename(fname))
        outer.attach(msg)
    return outer.as_string()
157675
private void completeMultiPartUpload() throws IOException {
    AmazonClientException lastException;
    CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest(mBucketName,
        mKey, mUploadId, mTags);
    do {
      try {
        mClient.completeMultipartUpload(completeRequest);
        LOG.debug("Completed multipart upload for key {} and id '{}' with {} partitions.",
            mKey, mUploadId, mTags.size());
        return;
      } catch (AmazonClientException e) {
        lastException = e;
      }
    } while (mRetryPolicy.attempt());
    // This point is only reached if the operation failed more
    // than the allowed retry count
    throw new IOException("Unable to complete multipart upload with id '"
        + mUploadId + "' to " + mKey, lastException);
  }
705220
def put(self, filename, totalChunks, status):
        
        logger.info('Completing ' + filename + ' - ' + status)
        self._uploadController.finalise(filename, int(totalChunks), status)
        return None, 200
222873
def update_media_file(upload_file):
    '''
    
    '''
    temp_directory = tempfile.mkdtemp()
    temp_file = tempfile.TemporaryFile()
    # assumes the zip file contains a directory called media
    temp_media_file = os.path.join(temp_directory, 'media')
    try:
        for chunk in upload_file.chunks():
            temp_file.write(chunk)

        with zipfile.ZipFile(temp_file, 'r') as z:
            z.extractall(temp_directory)

        if os.path.exists(temp_media_file):
            return distutils.dir_util.copy_tree(
                temp_media_file,
                settings.MEDIA_ROOT)
        else:
            raise Exception("Error: There is no directory called "
                            "'media' in the root of the zipped file")
    except Exception as e:
        raise e
    finally:
        temp_file.close()
        if os.path.exists(temp_directory):
            shutil.rmtree(temp_directory)
1356417
def put_files(self, files, content_type=None, compress=None, cache_control=None, block=True):
    
    for path, content in tqdm(files, disable=(not self.progress), desc="Uploading"):
      content = compression.compress(content, method=compress)
      self._interface.put_file(path, content, content_type, compress, cache_control=cache_control)
    return self
477059
function finalizeSection() {
            if (lastSectionDoc) {
                self._$headers[lastSectionDoc.file.fullPath].append(" (" + numItemsInSection + ")");
                if (self._collapsedFiles[lastSectionDoc.file.fullPath]) {
                    self._toggleSection(lastSectionDoc.file.fullPath, true);
                }
            }
        }
111011
def _finalize_upload(self, ud):
        # type: (Uploader, blobxfer.models.upload.Descriptor) -> None
        
        metadata = ud.generate_metadata()
        if ud.requires_put_block_list:
            # put block list for non one-shot block blobs
            self._finalize_block_blob(ud, metadata)
        elif ud.remote_is_page_blob or ud.remote_is_append_blob:
            # append and page blob finalization
            self._finalize_nonblock_blob(ud, metadata)
        elif ud.remote_is_file:
            # azure file finalization
            self._finalize_azure_file(ud, metadata)
        # set access tier
        if ud.requires_access_tier_set:
            blobxfer.operations.azure.blob.block.set_blob_access_tier(
                ud.entity)
434646
def _finalize_upload(self):
        
        from sevenbridges.models.file import File
        try:
            response = self._api.post(
                self._URL['upload_complete'].format(upload_id=self._upload_id)
            ).json()
            self._result = File(api=self._api, **response)
            self._status = TransferState.COMPLETED

        except SbgError as e:
            self._status = TransferState.FAILED
            raise SbgError(
                'Failed to complete upload! Reason: {}'.format(e.message)
            )