Handle files upload
file on model is a helper field
@author Wojciech Jurkowski <w.jurkowski@holonglobe.com>
8647
public function upload(FileRequest $request)
    {
        $crudeName = $request->input('crudeName');
        $crude = CrudeInstance::get($crudeName);
        $files = $request->file()['file'];
        $id = $request->input('modelId');
        $errors = [];

        if ($crude instanceof \JanDolata\CrudeCRUD\Engine\Interfaces\WithValidationInterface) {
            foreach($files as $key => $file) {
                $rules = $crude->getValidationRules(['file']);

                $mime = $file->getMimeType();
                $fileTypeRules = 'file_'.collect(explode('/', $mime))->first();

                empty($crude->getValidationRules([$fileTypeRules])[$fileTypeRules])
                    ? $rules = $rules
                    : $rules['file'] = $rules['file'] . '|' . $crude->getValidationRules([$fileTypeRules])[$fileTypeRules];

                $validator = Validator::make(['file' => $file], $rules);

                if ($validator->fails()) {
                    unset($files[$key]);
                    $errors[] = $file->getClientOriginalName() . ': '. $validator->messages()->first();
                }
            }
        }

        $model = empty($files)
            ? $crude->getById($id)
            : $crude->uploadFilesById($id, $files);

        $response = ['success' => true, 'model' => $model];

        if (!empty($errors)) {
            $response = array_merge($response, ['errors' => join('<br/>', $errors)]);
            $response['success'] = false;
        }

        return $response;
    }
631704
def handle_upload(repo, **kwargs):
    
    log.info('upload: %s' %(repo))
    name = kwargs.get('filename', 'Untitled')
    data = kwargs.get('filedata')
    repo.addItem(Item.from_string(repo=repo, name=name, string=data))
1335928
void handleAdd() {
        BoofSwingUtil.checkGuiThread();
        java.util.List<File> paths = browser.getSelectedFiles();

        for (int i = 0; i < paths.size(); i++) {
            File f = paths.get(i);

            // if it's a directory add all the files in the directory
            if( f.isDirectory() ) {
                java.util.List<String> files = UtilIO.listAll(f.getPath());
                Collections.sort(files);
                for (int j = 0; j < files.size(); j++) {
                    File p = new File(files.get(j));
                    // Note: Can't use mimetype to determine if it's an image or not since it isn't 100% reliable
                    if( p.isFile() ) {
                        selected.addPath(p);
                    }
                }
            } else {
                selected.addPath(f);
            }
        }
    }
1334824
def _handle_files(self, data):
        """"""

        initial = data.get("set", False)
        files = data["files"]
        for f in files:
            try:
                fobj = File(
                    self.room,
                    self.conn,
                    f[0],
                    f[1],
                    type=f[2],
                    size=f[3],
                    expire_time=int(f[4]) / 1000,
                    uploader=f[6].get("nick") or f[6].get("user"),
                )
                self.room.filedict = fobj.fid, fobj
                if not initial:
                    self.conn.enqueue_data("file", fobj)
            except Exception:
                import pprint

                LOGGER.exception("bad file")
                pprint.pprint(f)
        if initial:
            self.conn.enqueue_data("initial_files", self.room.files)
418717
function(el, settings) {
    this.setSettings(settings);
    this.manager = this.settings.manager || new FileUploadManager(this.settings);
    this.setElement(el);
}
1132245
private function handleCustomFileTree(&$arrFieldDef)
    {
        if ($this->get('file_uploadFolder')) {
            // Set root path of file chooser depending on contao version.
            $file = null;

            if ($this->validator->isUuid($this->get('file_uploadFolder'))) {
                $file = $this->fileRepository->findByUuid($this->get('file_uploadFolder'));
            }

            // Check if we have a file.
            if (null !== $file) {
                $arrFieldDef['eval']['path'] = $file->path;
            } else {
                // Fallback.
                $arrFieldDef['eval']['path'] = $this->get('file_uploadFolder');
            }
        }

        if ($this->get('file_validFileTypes')) {
            $arrFieldDef['eval']['extensions'] = $this->get('file_validFileTypes');
        }

        if ($this->get('file_filesOnly')) {
            $arrFieldDef['eval']['filesOnly'] = true;
        }
    }
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
785280
public function saveFiles(&$current_model)
    {
        foreach ($current_model->getAttributes() as $attribute => $value){
            if($current_model->hasValidator('image', $attribute)) {
                $current_model->$attribute = UploadedFile::getInstance($current_model, $attribute);
                if($current_model->$attribute && $current_model->validate([$attribute])){
                    $current_model->$attribute = Image::upload($current_model->$attribute, $current_model::SLUG);
                }
                else{
                    $current_model->$attribute = $current_model->isNewRecord ? '' : $current_model->oldAttributes[$attribute];
                }
            }elseif ($current_model->hasValidator('file', $attribute)){
                if($fileInstanse = UploadedFile::getInstance($current_model, $attribute)) {
                    $current_model->$attribute = Upload::file($fileInstanse, $current_model::SLUG);
                }else{
                    $current_model->$attribute = $current_model->isNewRecord ? '' : $current_model->oldAttributes[$attribute];
                }
            }
        }
    }
801303
function upload(file_mngr_url, file, filename, success, error) {
    // Assemble data
    var fd = new FormData();
    fd.append("filename", filename);
    fd.append("file", file);
    var req = new XMLHttpRequest();
    req.open("POST", file_mngr_url + "/upload");
    req.onload = function(e) {
        var url = JSON.parse(req.response).url;
        if (url === undefined)
            error();
        else
            success(url);
    };
    req.send(fd);
}
1285323
public function fileUpload()
    {
        $this->element = Angular::fileUpload('{model}', '{label}', [
            'fieldid' => $this->form->getFieldId($this->attribute),
            'ng-init' => '{initValue}',
        ]);

        return $this;
    }
1368339
def process_fields(file_path, task_id = task[:id], options = {})
      RestClient.post("#{url}/processFields?taskId=#{task_id}", options.merge(:upload => { :file => File.new(file_path, 'r') }))
    end
477285
protected function autoUpload()
    {
        foreach ($this->getDefinedUploadFields() as $key => $val) {
            $field = is_int($key) ? $val : $key;
            $options = array_wrap($val);

            // check if global upload is allowed, then in override in option
            $autoUploadAllowed = array_get($options, 'auto_upload', $this->canAutoUploadImages());

            if (!$autoUploadAllowed) {
                continue;
            }

            // get the input file name
            $requestFileName = array_get($options, 'file_input', $field);

            // if request has the file upload it
            if (request()->hasFile($requestFileName)) {
                $this->uploadImage(
                    request()->file($requestFileName),
                    $field
                );
            }
        }
    }
201995
function uploadFiles(files) {
    var index = 0,
        file = files[index];

    /**
    * Recursive helper used as callback for server.raw(put)
    * @param {error} err - Error message if something went wrong
    */
    var processFile = function processFile (err) {
      if (err) {
        grunt.log.warn(messages.fileTransferFail(file.dest, err));
      } else {
        grunt.log.ok(messages.fileTransferSuccess(file.dest));
      }

      ++index;
      // If there are more files, then keep pushing
      if (index < files.length) {
        file = files[index];
        server.put(grunt.file.read(file.src, { encoding: null }), file.dest, processFile);
      } else {
        // Close the connection, we are complete
        server.raw('quit', function(quitErr) {
          if (quitErr) {
            grunt.log.error(quitErr);
            done(false);
          }
          server.destroy();
          grunt.log.ok(messages.connectionClosed);
          done();
        });
      }
    };

    // Start uploading files
    server.put(grunt.file.read(file.src, { encoding: null }), file.dest, processFile);
  }
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();
    }
552999
public function process($field = null)
    {
        $uploadFiles = input()->files($field);

        if ( ! is_array($uploadFiles)) {
            $uploadFiles = [$uploadFiles];
        }

        if (count($uploadFiles)) {
            foreach ($uploadFiles as $file) {
                if ($file instanceof UploadFile) {
                    if (defined('PATH_STORAGE')) {
                        if ($this->path === PATH_STORAGE) {
                            if (strpos($file->getClientMediaType(), 'image') !== false) {
                                $this->path = $this->path . 'images' . DIRECTORY_SEPARATOR;
                            } else {
                                $this->path = $this->path . 'files' . DIRECTORY_SEPARATOR;
                            }
                        }
                    }

                    $targetPath = $this->path;

                    if (empty($this->targetFilename)) {
                        $this->setTargetFilename($file->getClientFilename());
                    }

                    $filename = $this->targetFilename;

                    if ($this->validate($file)) {
                        if ( ! is_file($filePath = $targetPath . $filename . '.' . $file->getExtension())) {
                            $this->move($file, $filePath);
                        } elseif ( ! is_file($filePath = $targetPath . $filename . '-1' . '.' . $file->getExtension())) {
                            $this->move($file, $filePath);
                        } else {
                            $existingFiles = glob($targetPath . $filename . '*.' . $file->getExtension());
                            if (count($existingFiles)) {
                                $increment = count($existingFiles) - 1;
                            }

                            foreach (range($increment + 1, $increment + 3, 1) as $increment) {
                                if ($increment > $this->maxIncrementFilename) {
                                    $this->errors[] = language()->getLine(
                                        'UPLOADER_E_MAXIMUM_INCREMENT_FILENAME',
                                        [$file->getClientFilename()]
                                    );
                                }

                                if ( ! is_file($filePath = $targetPath . $filename . '-' . $increment . '.' . $file->getExtension())) {
                                    $this->move($file, $filePath);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (count($this->errors) == 0) {
                return true;
            }
        }

        return false;
    }
963114
function handleFile(name, file, options, cache, callback) {
	var cachedData;
	if(!options || !options.settings || options.settings['view cache'] !== false) {
		cachedData = cache && cache.get(file);
	}
	if (!cachedData) {
		loadFile(file, function(err, fileData) {
			if (err) {
				return callback(err);
			}

			var partials;
			try {
				partials = findPartials(fileData);
			} catch (err) {
				return callback(err);
			}

			var data = {
				name: name,
				data: fileData,
				partials: partials
			};
			if (cache) {
				cache.set(file, data);
			}
			return callback(null, data);
		});
	}
	else {
		return callback(null, cachedData);
	}
}
1362290
public function renderField()
    {
        list($name, $id) = $this->resolveNameID();

        TbArray::defaultValue('id', $id, $this->htmlOptions);
        TbArray::defaultValue('name', $name, $this->htmlOptions);
        $this->htmlOptions['data-url'] = $this->uploadAction;
        $this->pluginOptions['url'] = $this->uploadAction;
        if ($this->hasModel()) {
            echo CHtml::activeFileField($this->model, $this->attribute, $this->htmlOptions);

        } else {
            echo CHtml::fileField($name, $this->value, $this->htmlOptions);
        }
    }