Upload a file to a temporary location.

    Flask will not load sufficiently large files into memory, so it
    makes sense to always load files into a temporary directory.
969607
def temporary_upload(name, fileobj):
    
    tempdir = mkdtemp()
    filename = secure_filename(fileobj.filename)
    filepath = join(tempdir, filename)
    fileobj.save(filepath)
    try:
        yield name, filepath, fileobj.filename
    finally:
        rmtree(tempdir)
471844
def createTempFile(self, suffix=None, prefix=None, secure=True) -> 'File':
        
        if not secure:
            raise NotImplementedError("We only support secure files at this point")

        # tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

        newFileNum, newFileRealPath = tempfile.mkstemp(
            suffix=suffix, prefix=prefix, dir=self._path)
        os.close(newFileNum)

        relativePath = os.path.relpath(newFileRealPath, self.path)

        file = File(self, pathName=relativePath, exists=True)
        self._files[file.pathName] = file
        return file
405014
def _local_upload(self, filepath, remove=False):
        """"""
        if os.path.isfile(filepath):
            filename = os.path.basename(os.path.abspath(filepath))
            if filename and self.__isValidFilename(filename):
                suffix = self.__getFilenameSuffix(filename)
                try:
                    self.__unpack_tgz(os.path.abspath(filepath)) if self.__isValidTGZ(suffix) else self.__unpack_zip(os.path.abspath(filepath))
                finally:
                    if remove is True:
                        os.remove(filepath)
            else:
                raise InstallError("Invalid Filename")
        else:
            raise InstallError("Invalid Filepath")
128691
def upload_file(self, file_name, file_path):
        
        upload_key = Key(bucket=self.bucket, name=file_name)
        content_type = "text/plain"
        if file_name.endswith(".html"):
            content_type = "text/html"
        elif file_name.endswith(".jpg"):
            content_type = "image/jpeg"
        elif file_name.endswith(".png"):
            content_type = "image/png"
        upload_key.set_contents_from_filename(
            file_path,
            headers={"Content-Type": content_type})
        upload_key.url = \
            upload_key.generate_url(expires_in=3600).split("?")[0]
        try:
            upload_key.make_public()
        except Exception:
            pass
1353829
def process_temporary_file(self, tmp_file):
        """"""

        #Truncate filename if necessary
        if len(tmp_file.filename) > 100:
            base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")]
            tmp_file.filename = "%s.%s" % (base_filename[:99-len(tmp_file.extension)], tmp_file.extension)

        tmp_file.save()

        data = {
            'uuid': str(tmp_file.uuid)
        }

        response = HttpResponse(json.dumps(data), status=201)
        response['Content-type'] = "text/plain"

        return response
1187809
def deploy_to_s3(self):
        
        self.tempdir = tempfile.mkdtemp('s3deploy')

        for keyname, absolute_path in self.find_file_paths():
            self.s3_upload(keyname, absolute_path)

        shutil.rmtree(self.tempdir, True)
        return True
1066658
def serve(content):
    """"""
    temp_folder = tempfile.gettempdir()
    temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
    # Generate a file path with a random name in temporary dir
    temp_file_path = os.path.join(temp_folder, temp_file_name)

    # save content to temp file
    save(temp_file_path, content)

    # Open templfile in a browser
    webbrowser.open("file://{}".format(temp_file_path))

    # Block the thread while content is served
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        # cleanup the temp file
        os.remove(temp_file_path)
32471
def upload(path, body, options={})
      options[:client_modified] = Time.now.utc.iso8601
      options[:path] = path
      resp = upload_request('/files/upload', body, options.merge(path: path))
      FileMetadata.new(resp)
    end
305650
def _copy_body_to_tempfile(cls, environ):
        
        try:
            length = int(environ.get('CONTENT_LENGTH', 0))
        except ValueError:
            length = 0

        try:
            fileobj = tempfile.SpooledTemporaryFile(1024*1024)
        except AttributeError:  # pragma: nocover
            fileobj = tempfile.TemporaryFile()  # py25 fallback
        if length:
            remaining = length
            while remaining > 0:
                data = environ['wsgi.input'].read(min(remaining, 65536))
                if not data:
                    raise IOError(
                        "Client disconnected (%s more bytes were expected)"
                        % remaining
                    )
                fileobj.write(data)
                remaining -= len(data)

        fileobj.seek(0)
        environ['wsgi.input'] = fileobj
        return fileobj, length
735921
private void putFile(String name, UploadFile uploadFile) {
		UploadFile[] fileUploads = requestFiles.get(name);
		fileUploads = fileUploads == null ? new UploadFile[] { uploadFile } : ArrayUtil.append(fileUploads, uploadFile);
		requestFiles.put(name, fileUploads);
	}
1140898
def upload_file(self, container, src_file_path, dst_name=None, put=True,
                    content_type=None):
        """"""
        if not os.path.exists(src_file_path):
            raise RuntimeError('file not found: ' + src_file_path)
        if not dst_name:
            dst_name = os.path.basename(src_file_path)
        if not content_type:
            content_type = "application/octet.stream"
        headers = dict(self._base_headers)
        if content_type:
            headers["content-length"] = content_type
        else:
            headers["content-length"] = "application/octet.stream"
        headers["content-length"] = str(os.path.getsize(src_file_path))
        headers['content-disposition'] = 'attachment; filename=' + dst_name
        if put:
            method = 'PUT'
            url = self.make_url(container, dst_name, None)
        else:
            method = 'POST'
            url = self.make_url(container, None, None)
        with open(src_file_path, 'rb') as up_file:
            try:
                rsp = requests.request(method, url, headers=headers,
                                       data=up_file, timeout=self._timeout)
            except requests.exceptions.ConnectionError as e:
                RestHttp._raise_conn_error(e)

        return self._handle_response(rsp)
914186
def upload_file(self, file_name, file_obj, *args, **kwargs):
		
		previous_path = self.session_path()
		try:
			self.session_path(file_name)
			with open(self.full_path(), mode='wb') as f:
				chunk = file_obj.read(io.DEFAULT_BUFFER_SIZE)
				while len(chunk) > 0:
					f.write(chunk)
					chunk = file_obj.read(io.DEFAULT_BUFFER_SIZE)
		finally:
			self.session_path(previous_path)
871699
def upload(self, local, remote):
        
        self.sync(LocalFile(local), RemoteFile(remote, self.api))
1051149
def put_file(self, in_path, out_path):
        
        try:
            st = os.stat(in_path)
        except OSError as e:
            self._throw_io_error(e, in_path)
            raise

        if not stat.S_ISREG(st.st_mode):
            raise IOError('%r is not a regular file.' % (in_path,))

        # If the file is sufficiently small, just ship it in the argument list
        # rather than introducing an extra RTT for the child to request it from
        # FileService.
        if st.st_size <= self.SMALL_FILE_LIMIT:
            try:
                fp = open(in_path, 'rb')
                try:
                    s = fp.read(self.SMALL_FILE_LIMIT + 1)
                finally:
                    fp.close()
            except OSError:
                self._throw_io_error(e, in_path)
                raise

            # Ensure did not grow during read.
            if len(s) == st.st_size:
                return self.put_data(out_path, s, mode=st.st_mode,
                                     utimes=(st.st_atime, st.st_mtime))

        self._connect()
        self.parent.call_service(
            service_name='mitogen.service.FileService',
            method_name='register',
            path=mitogen.utils.cast(in_path)
        )

        # For now this must remain synchronous, as the action plug-in may have
        # passed us a temporary file to transfer. A future FileService could
        # maintain an LRU list of open file descriptors to keep the temporary
        # file alive, but that requires more work.
        self.get_chain().call(
            ansible_mitogen.target.transfer_file,
            context=self.parent,
            in_path=in_path,
            out_path=out_path
        )
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();
    }
1003961
def storeAssociation(self, server_url, association):
        
        association_s = association.serialize()  # NOTE: UTF-8 encoded bytes
        filename = self.getAssociationFilename(server_url, association.handle)
        tmp_file, tmp = self._mktemp()

        try:
            try:
                tmp_file.write(association_s)
                os.fsync(tmp_file.fileno())
            finally:
                tmp_file.close()

            try:
                os.rename(tmp, filename)
            except OSError as why:
                if why.errno != EEXIST:
                    raise

                # We only expect EEXIST to happen only on Windows. It's
                # possible that we will succeed in unlinking the existing
                # file, but not in putting the temporary file in place.
                try:
                    os.unlink(filename)
                except OSError as why:
                    if why.errno == ENOENT:
                        pass
                    else:
                        raise

                # Now the target should not exist. Try renaming again,
                # giving up if it fails.
                os.rename(tmp, filename)
        except:
            # If there was an error, don't leave the temporary file
            # around.
            _removeIfPresent(tmp)
            raise
1255793
protected function saveToTempFile()
    {
        // Convert uploaded file to an array
        $aFiles = [];
        foreach($this->aUserFiles as $sVarName => $aUserFiles)
        {
            $aFiles[$sVarName] = [];
            foreach($aUserFiles as $aUserFile)
            {
                 $aFiles[$sVarName][] = $aUserFile->toTempData();
            }
        }
        // Save upload data in a temp file
        $sUploadDir = $this->getUploadTempDir();
        $this->sTempFile = uniqid();
        file_put_contents($sUploadDir . $this->sTempFile . '.json', json_encode($aFiles));
    }