Handles a file upload.
176597
private void handleUpload(AsyncFile file, String address, Handler<AsyncResult<Void>> doneHandler) {
    vertx.eventBus().registerHandler(address, handleUpload(file, address), doneHandler);
  }
684577
def upload_file(self, file):
        """"""

        url = self._get_url('/api/1.0/upload/post')

        fcontent = FileContent(file)
        binary_data = fcontent.get_binary()

        headers = self._get_request_headers()
        req = urllib.request.Request(url, binary_data, headers)
        req.add_header('Content-type', fcontent.get_content_type())
        req.add_header('Content-length', len(binary_data))
        resp = urllib.request.urlopen(req)   

        return definition.UploadPostResponse(_response_to_json(resp))
265863
public void submit() {

        // create a JsArray containing the files to upload
        List<CmsFileInfo> filesToUpload = new ArrayList<CmsFileInfo>(getFilesToUpload().values());
        Collections.sort(filesToUpload, CmsFileInfo.INFO_COMPARATOR);

        CmsUploader uploader = new CmsUploader();
        uploader.uploadFiles(
            getUploadUri(),
            getTargetFolder(),
            m_isTargetRootPath,
            filesToUpload,
            getFilesToUnzip(false),
            this);
    }
155666
protected function process()
    {

        // query whether or not we've the flag to upload the image files has been set
        if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::COPY_IMAGES)) {
            // query whether or not we've to upload the image files
            if ($this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::COPY_IMAGES)) {
                // initialize the array for the actual images
                $actualImageNames = array();

                // iterate over the available image fields
                foreach (array_keys($this->getImageTypes()) as $imageColumnName) {
                    // do nothing if the column is empty
                    if (!$this->hasValue($imageColumnName)) {
                        continue;
                    }

                    // override the image path with the new one, if the image has already been processed
                    if (isset($actualImageNames[$imageName = $this->getValue($imageColumnName)])) {
                        $this->setValue($imageColumnName, $actualImageNames[$imageName]);
                        continue;
                    }

                    // upload the file and set the new image path
                    $imagePath = $this->getSubject()->uploadFile($imageName);

                    // log a message that the image has been copied
                    $this->getSubject()
                         ->getSystemLogger()
                         ->debug(
                             sprintf(
                                 'Successfully copied image type %s with name %s => %s',
                                 $imageColumnName,
                                 $imageName,
                                 $imagePath
                             )
                         );

                    // override the image path with the new one
                    $this->setValue($imageColumnName, $imagePath);

                        // add the image to the list with processed images
                    $actualImageNames[$imageName] = $imagePath;
                }

                // query whether or not, we've additional images
                if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
                    // process all the additional images
                    foreach ($additionalImages as $key => $additionalImageName) {
                        // query whether or not the image has already been processed
                        if (isset($actualImageNames[$additionalImageName])) {
                            // if yes, override the image path
                            $additionalImages[$key] = $imagePath;
                            // and override the image path with the new one
                            $this->setValue($imageColumnName, $actualImageNames[$additionalImageName]);
                            continue;
                        }

                        // upload the file and set the new image path
                        $imagePath = $this->getSubject()->uploadFile($additionalImageName);

                        // log a message that the image has been copied
                        $this->getSubject()
                             ->getSystemLogger()
                             ->debug(
                                 sprintf(
                                     'Successfully copied additional image wth name %s => %s',
                                     $additionalImageName,
                                     $imagePath
                                 )
                             );

                        // override the image path
                        $additionalImages[$key] = $imagePath;

                        // add the image to the list with processed images
                        $actualImageNames[$additionalImageName] = $imagePath;
                    }

                    // override the image paths with the new one
                    $this->setValue(ColumnKeys::ADDITIONAL_IMAGES, implode(',', $additionalImages));
                }
            }
        }
    }
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);
	}
787844
public function handleUpload(\Illuminate\Http\Request $request, $fieldname = 'photo', $folder = 'images', $storage_disk = 'public', $randomize = true){
        if(is_null($request->file($fieldname)) || !$request->file($fieldname)->isValid()){
            throw new \Exception(trans('crud.invalid_file_upload'));
        }
        //Get filename
        $basename = basename($request->file($fieldname)->getClientOriginalName(),'.'.$request->file($fieldname)->getClientOriginalExtension());
        if($randomize){
            $filename = uniqid().'_'.str_slug($basename).'.'.$request->file($fieldname)->getClientOriginalExtension();
        }
        else{
            $filename = str_slug($basename).'.'.$request->file($fieldname)->getClientOriginalExtension();
        }
        //Move file to location
        $request->file($fieldname)->storeAs($folder,$filename,$storage_disk);
        return $filename;
    }
110619
private Handler<Message<Buffer>> handleUpload(final AsyncFile file, final String address) {
    final AtomicLong position = new AtomicLong();
    return new Handler<Message<Buffer>>() {
      @Override
      public void handle(final Message<Buffer> message) {
        final Handler<Message<Buffer>> handler = this;
        final Buffer buffer = message.body();
        if (buffer.length() > 0) {
          file.write(buffer, position.get(), new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                file.close();
                message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                vertx.eventBus().unregisterHandler(address, handler);
              } else {
                position.addAndGet(buffer.length());
                message.reply(new JsonObject().putString("status", "ok"));
              }
            }
          });
        } else {
          file.flush(new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                vertx.eventBus().unregisterHandler(address, handler);
              } else {
                file.close(new Handler<AsyncResult<Void>>() {
                  @Override
                  public void handle(AsyncResult<Void> result) {
                    if (result.failed()) {
                      message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                      vertx.eventBus().unregisterHandler(address, handler);
                    } else {
                      vertx.eventBus().unregisterHandler(address, handler, new Handler<AsyncResult<Void>>() {
                        @Override
                        public void handle(AsyncResult<Void> result) {
                          message.reply(new JsonObject().putString("status", "ok"));
                        }
                      });
                    }
                  }
                });
              }
            }
          });
        }
      }
    };
  }
250131
def handle_request_files_upload(request):
    
    # FILES is a dictionary in Django but Ajax Upload gives the uploaded file
    # an ID based on a random number, so it cannot be guessed here in the code.
    # Rather than editing Ajax Upload to pass the ID in the querystring,
    # note that each upload is a separate request so FILES should only
    # have one entry.
    # Thus, we can just grab the first (and only) value in the dict.
    is_raw = False
    upload = list(request.FILES.values())[0]
    filename = upload.name
    return upload, filename, is_raw
608973
def upload_file(upload_url, upload_fields, filepath, callback=None):
    """"""
    upload_fields = list(six.iteritems(upload_fields))
    upload_fields.append(
        ("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
    )
    encoder = MultipartEncoder(upload_fields)
    monitor = MultipartEncoderMonitor(encoder, callback=callback)

    config = cloudsmith_api.Configuration()
    if config.proxy:
        proxies = {"http": config.proxy, "https": config.proxy}
    else:
        proxies = None

    headers = {"content-type": monitor.content_type}

    client = get_files_api()
    headers["user-agent"] = client.api_client.user_agent

    session = create_requests_session()
    resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies)

    try:
        resp.raise_for_status()
    except requests.RequestException as exc:
        raise ApiException(
            resp.status_code, headers=exc.response.headers, body=exc.response.content
        )
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());
  }
644217
def handle_chunk(self, status, name, content, file_info):
        ""
        if status == "error":
            msg = repr(file_info.get("message"))
            exc = JavaScriptError(msg)
            exc.file_info = file_info
            self.status = "Javascript sent exception " + msg
            self.chunk_collector = []
            raise exc
        if status == "more":
            self.chunk_collector.append(content)
            self.progress_callback(self.chunk_collector, file_info)
        else:
            assert status == "done", "Unknown status " + repr(status)
            self.save_chunks = self.chunk_collector
            self.chunk_collector.append(content)
            all_content = self.combine_chunks(self.chunk_collector)
            self.chunk_collector = []
            content_callback = self.content_callback
            if content_callback is None:
                content_callback = self.default_content_callback
            self.status = "calling " + repr(content_callback)
            try:
                content_callback(self.widget, name, all_content)
            except Exception as e:
                self.status += "\n" + repr(content_callback) + " raised " + repr(e)
                raise
390470
public function validate()
    {
        // Delete the file when requested
        if (true === $this->enableReset && $this->getPost($this->strName.'_reset')) {
            if (null !== ($fileModel = FilesModel::findByPk($this->varValue))) {
                $file = new File($fileModel->path);
                $file->delete();
            }

            unset($_FILES[$this->strName]);

            return;
        }

        // Handle file upload
        parent::validate();

        // Set the image as varValue
        $file = $_SESSION['FILES'][$this->strName];
        if (true === $file['uploaded']) {
            $this->varValue = StringUtil::uuidToBin($file['uuid']);
        } else {
            $this->blnSubmitInput = false;
        }
    }
773424
def file_upload(self, local_path, remote_path, l_st):
        """"""
        self.sftp.put(local_path, remote_path)
        self._match_modes(remote_path, l_st)
1255237
private void parseFileUpload(FileUpload fileUpload) throws IOException {
        if (!fileUpload.isCompleted()) {
            return;
        }
        FileItem fileItem = new FileItem();
        fileItem.setName(fileUpload.getName());
        fileItem.setFileName(fileUpload.getFilename());

        // Upload the file is moved to the specified temporary file,
        // because FileUpload will be release after completion of the analysis.
        // tmpFile will be deleted automatically if they are used.
        Path tmpFile = Files.createTempFile(
                Paths.get(fileUpload.getFile().getParent()), "blade_", "_upload");

        Path fileUploadPath = Paths.get(fileUpload.getFile().getPath());
        Files.move(fileUploadPath, tmpFile, StandardCopyOption.REPLACE_EXISTING);

        fileItem.setFile(tmpFile.toFile());
        fileItem.setPath(tmpFile.toFile().getPath());
        fileItem.setContentType(fileUpload.getContentType());
        fileItem.setLength(fileUpload.length());

        fileItems.put(fileItem.getName(), fileItem);
    }
372324
def upload(self, url, filename, data=None, formname=None,
               otherfields=()):
        
        if data is None:
            data = open(filename, 'rb')
        self._upbuffer = StringIO.StringIO(get_upload_form(filename, data,
                                                           formname,
                                                           otherfields))
        ulheaders = self.stdheaders.copy()
        ulheaders['Content-Type'] = 'multipart/form-data; boundary=' + BND
        ulheaders['Content-Length'] = len(uploadforms[filename])
        self.ulsize = len(uploadforms[filename])
        webclient = self.dupe()
        webclient.request('POST', url, self._upbuffer, ulheaders)
        rsp = webclient.getresponse()
        # peer updates in progress should already have pointers,
        # subsequent transactions will cause memory to needlessly double,
        # but easiest way to keep memory relatively low
        try:
            del uploadforms[filename]
        except KeyError:  # something could have already deleted it
            pass
        self.rspstatus = rsp.status
        if rsp.status != 200:
            raise Exception('Unexpected response in file upload: ' +
                            rsp.read())
        return rsp.read()
673112
def process_upload(self, set_content_type=True):
        """"""
        metadata = self.get_upload_key_metadata()

        if set_content_type:
            content_type = self.get_upload_content_type()
            metadata.update({b'Content-Type': b'{0}'.format(content_type)})

        upload_key = self.get_upload_key()
        processed_key_name = self.get_processed_key_name()
        processed_key = upload_key.copy(upload_key.bucket.name,
                                        processed_key_name, metadata)
        processed_key.set_acl(self.get_processed_acl())
        upload_key.delete()
        return processed_key
997534
def upload_submit(self, upload_request):
        """"""

        path = '/api/1.0/upload/save'
        return self._api_post(definition.DatasetUploadResponse, path, upload_request)