Error occuring when the user try to upload a non-allowed file type
484538
def handle_unauthorized_file_type(error):
    ''''''
    url = url_for('api.allowed_extensions', _external=True)
    msg = (
        'This file type is not allowed.'
        'The allowed file type list is available at {url}'
    ).format(url=url)
    return {'message': msg}, 400
1186000
def upload_gallery_file(self, folder_name, file_name, data=None, input_file_path=None,
                            prevent_share=False, content_type="image/png", scope='content/write'):
        
        if input_file_path:
            with open(input_file_path, 'rb') as f:
                data = f.read()

        if not data:
            raise ValueError('Either the data of a file or the path to a file must be provided')

        params = {
            'fileName': file_name,
            'preventShare': 'true' if prevent_share else 'false',
        }

        return _post(
            token=self.oauth.get_user_token(scope),
            uri='/user/media/file/' + urllib.quote(folder_name) + '?' + urllib.urlencode(params),
            data=data,
            content_type=content_type,
        )
197316
def upload_file_handle(
            self,
            bucket: str,
            key: str,
            src_file_handle: typing.BinaryIO,
            content_type: str=None,
            metadata: dict=None):
        
        raise NotImplementedError()
1064616
def upload_asset(self, path, label="", content_type=""):
        
        assert isinstance(path, (str, unicode)), path
        assert isinstance(label, (str, unicode)), label

        post_parameters = {
            "name": basename(path),
            "label": label
        }
        headers = {}
        if len(content_type) > 0:
            headers["Content-Type"] = content_type
        resp_headers, data = self._requester.requestBlobAndCheck(
            "POST",
            self.upload_url.split("{?")[0],
            parameters=post_parameters,
            headers=headers,
            input=path
        )
        return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
1281866
def _set_upload_url(self):
        """"""
        # pylint: disable=protected-access
        self._upload_url = "/".join(
            [self.jss._url, self._url, self.resource_type, self.id_type,
             str(self._id)])
591079
function uploadByDir(src, dest, client) {
    ClientLib.scp(src, dest, client,
        function (err) {
            if (err) {
                console.log(err);
            }
        }
    );
}
485822
def create_non_data_file(self, params, file_data):
        '''
        
        '''
        api_prefix = '/api/imports2/'

        if not params.get('method', None):
            params['method'] = 'blob'

        return self._perform_request("post", api_prefix, params=params, files=file_data)
995388
def __allowed_extension(self, filename, extensions):
        
        allowed_extensions = current_app.config['UPLOADS']['EXTENSIONS']
        if extensions is not None:
            allowed_extensions = extensions
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in \
            allowed_extensions
180302
function onFile(__newFile, encoding, done) {
  var buffers = [];
  var options = this.options;

  // Check the file limit
  if (options.perMaxBytes && __newFile.byteCount > options.perMaxBytes) {
    return done(new Error('The file \'' + __newFile.filename + '\' beyond size limit, only accept less than ' + options.perMaxBytes + ' bytes'));
  }

  // Check the accept content type
  if (options.acceptTypes && options.acceptTypes.indexOf(__newFile.headers['content-type']) === -1) {
    return done(new Error('Content-type of the file \'' + __newFile.filename + '\' does not accepted'));
  }

  // Determine the file descriptor-- the unique identifier.
  // Often represents the location where file should be written.
  __newFile.fd;
  var uploadDir = __newFile.fd;
  if (uploadDir.substr(0, 1) !== '/') {
    uploadDir = '/' + uploadDir;
  }

  // When then 'data' event emited, push the chunk to the buffers array.
  __newFile.on('data', function (chunk) {
    buffers.push(chunk);
  });

  // When the 'end' event emited, upload the 'buffers' to the upyun server.
  __newFile.on('end', function () {
    var buffer = Buffer.concat(buffers);
    uploadToUpyun.bind({ options })(uploadDir, buffer, __newFile, done);
  });
}
1095517
def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors):
    """"""
    filename = click.format_filename(filepath)
    basename = os.path.basename(filename)

    click.echo(
        "Checking %(filename)s file upload parameters ... "
        % {"filename": click.style(basename, bold=True)},
        nl=False,
    )

    context_msg = "Failed to validate upload parameters!"
    with handle_api_exceptions(
        ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
    ):
        with maybe_spinner(opts):
            md5_checksum = validate_request_file_upload(
                owner=owner, repo=repo, filepath=filename
            )

    click.secho("OK", fg="green")

    return md5_checksum
730335
function errorMessage(fileError) {
        var msg = '';
        switch (fileError.code) {
            case FileError.NOT_FOUND_ERR:
                msg = 'File not found';
                break;
            case FileError.SECURITY_ERR:
                // You may need the --allow-file-access-from-files flag
                // if you're debugging your app from file://.
                msg = 'Security error';
                break;
            case FileError.ABORT_ERR:
                msg = 'Aborted';
                break;
            case FileError.NOT_READABLE_ERR:
                msg = 'File not readable';
                break;
            case FileError.ENCODING_ERR:
                msg = 'Encoding error';
                break;
            case FileError.NO_MODIFICATION_ALLOWED_ERR:
                msg = 'File not modifiable';
                break;
            case FileError.INVALID_STATE_ERR:
                msg = 'Invalid state';
                break;
            case FileError.SYNTAX_ERR:
                msg = 'Syntax error';
                break;
            case FileError.INVALID_MODIFICATION_ERR:
                msg = 'Invalid modification';
                break;
            case FileError.QUOTA_EXCEEDED_ERR:
                // You may need the --allow-file-access-from-files flag
                // if you're debugging your app from file://.
                msg = 'Quota exceeded';
                break;
            case FileError.TYPE_MISMATCH_ERR:
                msg = 'Type mismatch';
                break;
            case FileError.PATH_EXISTS_ERR:
                msg = 'File already exists';
                break;
            default:
                msg = 'Unknown FileError code (code= ' + fileError.code + ', type=' + typeof(fileError) + ')';
                break;
        }
        return msg;
    }
554683
def _submit(self, pathfile, filedata, filename):
		'''
		
		'''
		if pathfile and os.path.exists(pathfile):
			files = {'file': open(pathfile, 'rb')}
		elif filedata:
			assert filename
			files = {'file' : (filename, io.BytesIO(filedata))}
		else:
			raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!")

		payload = {
			'key'    : self.api_key,
			'method' : 'post',
			'json'   : True,
			}

		self.log.info("Uploading to 2Captcha.com.")

		url = self.getUrlFor('input', {})

		request = requests.post(url, files=files, data=payload)

		if not request.ok:
			raise exc.CaptchaSolverFailure("Posting captcha to solve failed!")

		resp_json = json.loads(request.text)
		return self._process_response(resp_json)
597611
function(_path, _type, _str){
        var file = $options.path+"/"+_path+"."+_type;
        $fs.appendFile(file, _str, 'utf8');
    }
602892
function error() {

                        this.httpRequest.upload.onerror = function onError() {

                            $scope.$apply(function apply() {

                                $scope.finishedUploading();
                                $scope.isError = true;

                                var response = $scope.options.parserFn(this.httpRequest.responseText);
                                $rootScope.$broadcast('$dropletError', response);
                                $scope.onError({ response: response });
                                this.deferred.reject(response);

                            }.bind(this));

                        }.bind(this);

                    }
408452
def import_action(self, request, *args, **kwargs):
        
        if not self.has_import_permission(request):
            raise PermissionDenied

        context = self.get_import_context_data()

        import_formats = self.get_import_formats()
        form_type = self.get_import_form()
        form_kwargs = self.get_form_kwargs(form_type, *args, **kwargs)
        form = form_type(import_formats,
                         request.POST or None,
                         request.FILES or None,
                         **form_kwargs)

        if request.POST and form.is_valid():
            input_format = import_formats[
                int(form.cleaned_data['input_format'])
            ]()
            import_file = form.cleaned_data['import_file']
            # first always write the uploaded file to disk as it may be a
            # memory file or else based on settings upload handlers
            tmp_storage = self.write_to_tmp_storage(import_file, input_format)

            # then read the file, using the proper format-specific mode
            # warning, big files may exceed memory
            try:
                data = tmp_storage.read(input_format.get_read_mode())
                if not input_format.is_binary() and self.from_encoding:
                    data = force_text(data, self.from_encoding)
                dataset = input_format.create_dataset(data)
            except UnicodeDecodeError as e:
                return HttpResponse(_(u"<h1>Imported file has a wrong encoding: %s</h1>" % e))
            except Exception as e:
                return HttpResponse(_(u"<h1>%s encountered while trying to read file: %s</h1>" % (type(e).__name__, import_file.name)))

            # prepare kwargs for import data, if needed
            res_kwargs = self.get_import_resource_kwargs(request, form=form, *args, **kwargs)
            resource = self.get_import_resource_class()(**res_kwargs)

            # prepare additional kwargs for import_data, if needed
            imp_kwargs = self.get_import_data_kwargs(request, form=form, *args, **kwargs)
            result = resource.import_data(dataset, dry_run=True,
                                          raise_errors=False,
                                          file_name=import_file.name,
                                          user=request.user,
                                          **imp_kwargs)

            context['result'] = result

            if not result.has_errors() and not result.has_validation_errors():
                initial = {
                    'import_file_name': tmp_storage.name,
                    'original_file_name': import_file.name,
                    'input_format': form.cleaned_data['input_format'],
                }
                confirm_form = self.get_confirm_import_form()
                initial = self.get_form_kwargs(form=form, **initial)
                context['confirm_form'] = confirm_form(initial=initial)
        else:
            res_kwargs = self.get_import_resource_kwargs(request, form=form, *args, **kwargs)
            resource = self.get_import_resource_class()(**res_kwargs)

        context.update(self.admin_site.each_context(request))

        context['title'] = _("Import")
        context['form'] = form
        context['opts'] = self.model._meta
        context['fields'] = [f.column_name for f in resource.get_user_visible_fields()]

        request.current_app = self.admin_site.name
        return TemplateResponse(request, [self.import_template_name],
                                context)
506703
function(options, cb) {
  if (os_name == 'windows') {
    path_arg = path.resolve(options.path);
    name_arg = path.resolve(options.name);
  } else {
    path_arg = '"' + options.path + '"';
    name_arg = '"' + options.name + '"';
  }
  var opts = {
    user: options.user,
    bin: node_bin,
    type: 'exec',
    args: [path.join(__dirname, 'upload.js'), path_arg, options.user, name_arg, options.size, options.file_id, options.total, options.port],
    opts: {
      env: process.env
    }
  };

  run_as_user(opts, function(err, out) {
    if (err) {
      logger.error("Upload error: " + err.message);
      return;
    }
    logger.info("Ran as user: " + out);
    if (out.indexOf("File succesfuly uploaded") != -1) {
      files.del(options.file_id);
      return;
    }
    if (out.includes("EPIPE") || out.includes("EACCES")) {
      files.update(options.file_id, options.path, options.size, options.user, options.name, options.resumable, function(err) {
        if (err) logger.error("Database update error");
        logger.info("Resume file option activated for ID: " + options.file_id);
      });
    }
  });
}
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