kandi background
Explore Kits

Filebase | A Simple but Powerful Flat File Database Storage | Database library

 by   tmarois PHP Version: v1.0.24 License: MIT

 by   tmarois PHP Version: v1.0.24 License: MIT

Download this library from

kandi X-RAY | Filebase Summary

Filebase is a PHP library typically used in Database applications. Filebase has no bugs, it has no vulnerabilities, it has a Permissive License and it has low support. You can download it from GitHub.
Join Discord – For support, updates and collaboration. A Simple but Powerful Flat File Database Storage. No need for MySQL or an expensive SQL server, in fact, you just need your current site or application setup. All database entries are stored in files (formatted the way you like). You can even modify the raw data within the files themselves without ever needing to use the API. And even better you can put all your files in version control and pass them to your team without having out-of-sync SQL databases. Doesn't that sound awesome?. With Filebase, you are in complete control. Design your data structure the way you want. Use arrays and objects like you know how in PHP. Update and share your data with others and teams using version control. Just remember, upgrading your web/apache server is a lot less than your database server. Works with PHP 5.6 and PHP 7+.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • Filebase has a low active ecosystem.
  • It has 244 star(s) with 44 fork(s). There are 20 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 18 open issues and 41 have been closed. On average issues are closed in 20 days. There are 3 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of Filebase is v1.0.24
Filebase Support
Best in #Database
Average in #Database
Filebase Support
Best in #Database
Average in #Database

quality kandi Quality

  • Filebase has 0 bugs and 119 code smells.
Filebase Quality
Best in #Database
Average in #Database
Filebase Quality
Best in #Database
Average in #Database

securitySecurity

  • Filebase has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • Filebase code analysis shows 0 unresolved vulnerabilities.
  • There are 8 security hotspots that need review.
Filebase Security
Best in #Database
Average in #Database
Filebase Security
Best in #Database
Average in #Database

license License

  • Filebase is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
Filebase License
Best in #Database
Average in #Database
Filebase License
Best in #Database
Average in #Database

buildReuse

  • Filebase releases are available to install and integrate.
  • Installation instructions, examples and code snippets are available.
  • Filebase saves you 1799 person hours of effort in developing the same functionality from scratch.
  • It has 3977 lines of code, 269 functions and 30 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
Filebase Reuse
Best in #Database
Average in #Database
Filebase Reuse
Best in #Database
Average in #Database
Top functions reviewed by kandi - BETA

kandi has reviewed Filebase and discovered the below as its top functions. This is intended to give you an instant insight into Filebase implemented functionality, and help decide if they suit your requirements.

  • Run the filter .
    • Get field value
      • Creates a zip archive .
        • Add new predicate
          • Checks the type of a variable
            • Find all files .
              • Sorts documents .
                • Get the cache
                  • Validate a file name .
                    • Json encode .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      Filebase Key Features

                      Key/Value and Array-based Data Storing

                      Querying data

                      Custom filters

                      Caching (queries)

                      Database Backups

                      Formatting (encode/decode)

                      Validation (on save)

                      CRUD (method APIs)

                      File locking (on save)

                      Intuitive Method Naming

                      Filebase Examples and Code Snippets

                      See all related Code Snippets

                      Usage

                      copy iconCopydownload iconDownload
                      // setting the access and configration to your database
                      $database = new \Filebase\Database([
                          'dir' => 'path/to/database/dir'
                      ]);
                      
                      // in this example, you would search an exact user name
                      // it would technically be stored as user_name.json in the directories
                      // if user_name.json doesn't exists get will return new empty Document
                      $item = $database->get('kingslayer');
                      
                      // display property values
                      echo $item->first_name;
                      echo $item->last_name;
                      echo $item->email;
                      
                      // change existing or add new properties
                      $item->email = 'example@example.com';
                      $item->tags  = ['php','developer','html5'];
                      
                      // need to save? thats easy!
                      $item->save();
                      
                      
                      // check if a record exists and do something if it does or does not
                      if ($database->has('kingslayer'))
                      {
                          // do some action
                      }
                      
                      // Need to find all the users that have a tag for "php" ?
                      $users = $db->where('tags','IN','php')->results();
                      
                      // Need to search for all the users who use @yahoo.com email addresses?
                      $users = $db->where('email','LIKE','@yahoo.com')->results();
                      
                      

                      (1) Config Options

                      copy iconCopydownload iconDownload
                      $db = new \Filebase\Database([
                          'dir'            => 'path/to/database/dir',
                          'backupLocation' => 'path/to/database/backup/dir',
                          'format'         => \Filebase\Format\Json::class,
                          'cache'          => true,
                          'cache_expires'  => 1800,
                          'pretty'         => true,
                          'safe_filename'  => true,
                          'read_only'      => false,
                          'validate' => [
                              'name'   => [
                                  'valid.type' => 'string',
                                  'valid.required' => true
                              ]
                          ]
                      ]);
                      

                      (2) Formatting

                      copy iconCopydownload iconDownload
                      \Filebase\Format\Json::class
                      

                      (3) GET (and methods)

                      copy iconCopydownload iconDownload
                      // my user id
                      $userId = '92832711';
                      
                      // get the user information by id
                      $item = $db->get($userId);
                      
                      

                      (4) Create | Update | Delete

                      copy iconCopydownload iconDownload
                      
                      // SAVE or CREATE
                      // this will save the current data and any changed variables
                      // but it will leave existing variables that you did not modify unchanged.
                      // This will also create a document if none exist.
                      $item->title = 'My Document';
                      $item->save()
                      
                      // This will replace all data within the document
                      // Allows you to reset the document and put in fresh data
                      // Ignoring any above changes or changes to variables, since
                      // This sets its own within the save method.
                      $item->save([
                          'title' => 'My Document'
                      ]);
                      
                      // DELETE
                      // This will delete the current document
                      // This action can not be undone.
                      $item->delete();
                      
                      

                      (5) Database Methods

                      copy iconCopydownload iconDownload
                      $db = new \Filebase\Database($config);
                      

                      (6) Validation

                      copy iconCopydownload iconDownload
                      $db = new \Filebase\Database([
                          'dir' => '/path/to/database/dir',
                          'validate' => [
                              'name'   => [
                                  'valid.type' => 'string',
                                  'valid.required' => true
                              ],
                              'description' => [
                                  'valid.type' => 'string',
                                  'valid.required' => false
                              ],
                              'emails' => [
                                  'valid.type'     => 'array',
                                  'valid.required' => true
                              ],
                              'config' => [
                                  'settings' => [
                                      'valid.type'     => 'array',
                                      'valid.required' => true
                                  ]
                              ]
                          ]
                      ]);
                      

                      (7) Custom Filters

                      copy iconCopydownload iconDownload
                      // Use [data] for all items within the document
                      // But be sure that each array item uses the same format (otherwise except isset errors)
                      
                      $users = $db->get('users')->filter('data','blocked',function($item, $status) {
                          return (($item['status']==$status) ? $item['email'] : false);
                      });
                      
                      // Nested Arrays?
                      // This uses NESTED properties. If the users array was stored as an array inside [list]
                      // You can also use `.` dot delimiter to get arrays from nested arrays
                      
                      $users = $db->get('users')->filter('list.users','blocked',function($item, $status) {
                          return (($item['status']==$status) ? $item['email'] : false);
                      });
                      

                      (8) Queries

                      copy iconCopydownload iconDownload
                      // Simple (equal to) Query
                      // return all the users that are blocked.
                      $users = $db->where(['status' => 'blocked'])->results();
                      
                      // Stackable WHERE clauses
                      // return all the users who are blocked,
                      // AND have "php" within the tag array
                      $users = $db->where('status','=','blocked')
                                  ->andWhere('tag','IN','php')
                                  ->results();
                      
                      // You can also use `.` dot delimiter to use on nested keys
                      $users = $db->where('status.language.english','=','blocked')->results();
                      
                      // Limit Example: Same query as above, except we only want to limit the results to 10
                      $users = $db->where('status.language.english','=','blocked')->limit(10)->results();
                      
                      
                      
                      // Query LIKE Example: how about find all users that have a gmail account?
                      $usersWithGmail = $db->where('email','LIKE','@gmail.com')->results();
                      
                      // OrderBy Example: From the above query, what if you want to order the results by nested array
                      $usersWithGmail = $db->where('email','LIKE','@gmail.com')
                                           ->orderBy('profile.name', 'ASC')
                                           ->results();
                      
                      // or just order the results by email address
                      $usersWithGmail = $db->where('email','LIKE','@gmail.com')
                                           ->orderBy('email', 'ASC')
                                           ->results();
                      
                      // OrderBy can be applied multiple times to perform a multi-sort
                      $usersWithGmail = $db->query()
                                          ->where('email','LIKE','@gmail.com')
                                          ->orderBy('last_name', 'ASC')
                                          ->orderBy('email', 'ASC')
                                          ->results();
                      
                      // this will return the first user in the list based on ascending order of user name.
                      $user = $db->orderBy('name','ASC')->first();
                      // print out the user name
                      echo $user['name'];
                      
                      // You can also order multiple columns as such (stacking)
                      $orderMultiples = $db->orderBy('field1','ASC')
                                           ->orderBy('field2','DESC')
                                           ->results();
                      
                      // What about regex search? Finds emails within a field
                      $users = $db->where('email','REGEX','/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i')->results();
                      
                      // Find all users that have gmail addresses and only returning their name and age fields (excluding the rest)
                      $users = $db->select('name,age')->where('email','LIKE','@gmail.com')->results();
                      
                      // Instead of returning users, how about just count how many users are found.
                      $totalUsers = $db->where('email','LIKE','@gmail.com')->count();
                      
                      
                      // You can delete all documents that match the query (BULK DELETE)
                      $db->where('name','LIKE','john')->delete();
                      
                      // Delete all items that match query and match custom filter
                      $db->where('name','LIKE','john')->delete(function($item){
                          return ($item->name == 'John' && $item->email == 'some@mail.com');
                      });
                      
                      
                      // GLOBAL VARIABLES
                      
                      // ability to sort the results by created at or updated at times
                      $documents = $db->orderBy('__created_at', 'DESC')->results();
                      $documents = $db->orderBy('__updated_at', 'DESC')->results();
                      
                      // search for items that match the (internal) id
                      $documents = $db->where('__id', 'IN', ['id1', 'id2'])->results();
                      
                      

                      Methods:

                      copy iconCopydownload iconDownload
                      // invoke your database
                      $database = new \Filebase\Database([
                          'dir' => '/storage/users',
                          'backupLocation' => '/storage/backup',
                      ]);
                      
                      // create a new backup of your database
                      // will look something like /storage/backup/1504631092.zip
                      $database->backup()->create();
                      
                      // delete all existing backups
                      $database->backup()->clean();
                      
                      // get a list of all existing backups (organized from new to old)
                      $backups = $database->backup()->find();
                      
                      // restore an existing backup (latest backup available)
                      $database->backup()->rollback();
                      
                      

                      postMessage validation failed error occurring during image upload using react-base64

                      copy iconCopydownload iconDownload
                      <FileBase type="file" multiple={false} onDone={({base64}) => setPostData({ ...postData, selectedFile: base64})} />
                      

                      Not Able to post asynchronously in react-redux

                      copy iconCopydownload iconDownload
                      export const createPost = (newPost) => {
                        return axios.post(url, newPost).then((res)=> res )
                      };
                      
                      export const createPost = (newPost) => axios.post(url, newPost);
                      
                      export const createPost = (newPost) => {
                        return axios.post(url, newPost).then((res)=> res )
                      };
                      
                      export const createPost = (newPost) => axios.post(url, newPost);
                      

                      dependency and option in meson project

                      copy iconCopydownload iconDownload
                      meson builddir -Dmysub:avx_opt=avx512
                      
                      meson configure builddir -Dmysub:avx_opt=avx512 
                      
                      option('avx_opt', ...., yield : true)
                      
                      meson configure builddir -Davx_opt=avx512
                      
                      meson builddir -Dmysub:avx_opt=avx512
                      
                      meson configure builddir -Dmysub:avx_opt=avx512 
                      
                      option('avx_opt', ...., yield : true)
                      
                      meson configure builddir -Davx_opt=avx512
                      
                      meson builddir -Dmysub:avx_opt=avx512
                      
                      meson configure builddir -Dmysub:avx_opt=avx512 
                      
                      option('avx_opt', ...., yield : true)
                      
                      meson configure builddir -Davx_opt=avx512
                      
                      meson builddir -Dmysub:avx_opt=avx512
                      
                      meson configure builddir -Dmysub:avx_opt=avx512 
                      
                      option('avx_opt', ...., yield : true)
                      
                      meson configure builddir -Davx_opt=avx512
                      

                      Problem with downloading image and displaying it

                      copy iconCopydownload iconDownload
                          var imageOutStream: OutputStream
                          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                              val values = ContentValues()
                              //image name
                              values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg");
                              // image type
                              values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                              //storage path
                              values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + "Camera");
                      
                              val uri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                              imageOutStream = uri?.let { requireContext().getContentResolver().openOutputStream(it) }!!
                          }
                      
                          else
                          {
                              //creating directory and saving
                              val imagesDir =
                                  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
                              val image = File(imagesDir, "image.jpg")
                              imageOutStream =  FileOutputStream(image);
                      
                          }
                          //compreesing the image
                          bmp.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
                          Toast.makeText(requireContext(),"ImageSaved",Toast.LENGTH_LONG).show()
                          imageOutStream.close();
                      
                      }`
                      
                      public async Task DownloadImage(string URL)
                      {
                          WebClient webClient = new WebClient();
                      
                          string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
                          string fileName = URL.ToString().Split('/').Last();
                          string filePath = Path.Combine(folderPath + "/", fileName);
                      
                          Preferences.Set("filePath", filePath);
                      
                          byte[] bytes = await webClient.DownloadDataTaskAsync(new Uri(""));
                          File.WriteAllBytes(filePath, bytes);
                        
                      }
                      
                      public void DownloadImage(string URL)
                      {
                          WebClient webClient = new WebClient();
                      
                          string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
                          string fileName = URL.ToString().Split('/').Last();
                          string filePath = Path.Combine(folderPath + "/", fileName);
                      
                          webClient.DownloadDataCompleted += (s, e) =>
                          {
                              byte[] bytes = new byte[e.Result.Length];
                              bytes = e.Result; // get the downloaded data
                              File.WriteAllBytes(filePath, bytes);
                      
                              //move to here
                              await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(filePath ) });
                      
                          };
                      
                          webClient.DownloadDataAsync(new Uri(URL));
                      }
                      
                      
                      imagen_tap.Tapped += (s, e) =>
                      {
                          string urlImage = url + Foto.ID_Parte + "/" + Foto.Archivo;
                          api.DownloadImage(urlImage);
                      };
                      
                      public async Task DownloadImage(string URL)
                      {
                          WebClient webClient = new WebClient();
                      
                          string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
                          string fileName = URL.ToString().Split('/').Last();
                          string filePath = Path.Combine(folderPath + "/", fileName);
                      
                          Preferences.Set("filePath", filePath);
                      
                          byte[] bytes = await webClient.DownloadDataTaskAsync(new Uri(""));
                          File.WriteAllBytes(filePath, bytes);
                        
                      }
                      
                      public void DownloadImage(string URL)
                      {
                          WebClient webClient = new WebClient();
                      
                          string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Images", "temp");
                          string fileName = URL.ToString().Split('/').Last();
                          string filePath = Path.Combine(folderPath + "/", fileName);
                      
                          webClient.DownloadDataCompleted += (s, e) =>
                          {
                              byte[] bytes = new byte[e.Result.Length];
                              bytes = e.Result; // get the downloaded data
                              File.WriteAllBytes(filePath, bytes);
                      
                              //move to here
                              await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(filePath ) });
                      
                          };
                      
                          webClient.DownloadDataAsync(new Uri(URL));
                      }
                      
                      
                      imagen_tap.Tapped += (s, e) =>
                      {
                          string urlImage = url + Foto.ID_Parte + "/" + Foto.Archivo;
                          api.DownloadImage(urlImage);
                      };
                      

                      uniqid() not generating unique values within a Foreach loop - PHP

                      copy iconCopydownload iconDownload
                      uniqid('', true)
                      

                      Moving files by their filenames

                      copy iconCopydownload iconDownload
                      library(stringr)
                      #Get all files
                      path <- 'k:/WF/LST/Surf_Temp_Monthly_005dg_v6/LST_Day_CMG/TEST'
                      
                      files <- list.files(path= path, pattern ="[0-9]{3}_20*", recursive = TRUE)
                      
                      move.file <- function(filename,to = '001') {
                        fromdir <- dirname(filename)
                        rootdir <- dirname(fromdir)
                        filebase <- basename(filename)
                        # File not in right directory
                        if (str_detect(filebase, regex(to, ignore_case = TRUE))&
                            !str_detect(fromdir, regex(to, ignore_case = TRUE))) {
                          dir.create(file.path(rootdir,to),showWarnings = F)
                          file.rename(from = file.path(path,filename),
                                      to = file.path(path,rootdir,to,filebase))
                        } else {F}
                      }
                      
                      for (i in seq_along(files)){
                           move.file(filename = files[i], to =sprintf("%03d",i))
                      }
                      

                      Problems reading an .rdb file in R

                      copy iconCopydownload iconDownload
                      ls()
                      # character(0)
                      lazyLoad("c:/Users/r2/R/win-library/4.0/yaml/help/yaml", envir = .GlobalEnv)
                      # NULL
                      ls()
                      # [1] "as.yaml"    "read_yaml"  "write_yaml" "yaml.load" 
                      as.yaml
                      # \title{ Convert an R object into a YAML string }\name{as.yaml}\alias{as.yaml}\keyword{ data }\keyword{ manip }\description{
                      #   Convert an R object into a YAML string
                      # }\usage{
                      #   as.yaml(x, line.sep = c("\n", "\r\n", "\r"), indent = 2, omap = FALSE,
                      #           column.major = TRUE, unicode = TRUE, precision = getOption('digits'),
                      #           indent.mapping.sequence = FALSE, handlers = NULL)
                      # }.......
                      
                      e <- new.env(parent = emptyenv())
                      lazyLoad("c:/Users/r2/R/win-library/4.0/yaml/help/yaml", envir = e)
                      # NULL
                      ls(e)
                      # [1] "as.yaml"    "read_yaml"  "write_yaml" "yaml.load" 
                      e$as.yaml
                      # \title{ Convert an R object into a YAML string }\name{as.yaml}\alias{as.yaml}\keyword{ data }\keyword{ manip }\description{
                      #   Convert an R object into a YAML string
                      # }\usage{
                      #   as.yaml(x, line.sep = c("\n", "\r\n", "\r"), indent = 2, omap = FALSE,
                      #           column.major = TRUE, unicode = TRUE, precision = getOption('digits'),
                      #           indent.mapping.sequence = FALSE, handlers = NULL)
                      # }......
                      
                      ls()
                      # character(0)
                      lazyLoad("c:/Users/r2/R/win-library/4.0/yaml/help/yaml", envir = .GlobalEnv)
                      # NULL
                      ls()
                      # [1] "as.yaml"    "read_yaml"  "write_yaml" "yaml.load" 
                      as.yaml
                      # \title{ Convert an R object into a YAML string }\name{as.yaml}\alias{as.yaml}\keyword{ data }\keyword{ manip }\description{
                      #   Convert an R object into a YAML string
                      # }\usage{
                      #   as.yaml(x, line.sep = c("\n", "\r\n", "\r"), indent = 2, omap = FALSE,
                      #           column.major = TRUE, unicode = TRUE, precision = getOption('digits'),
                      #           indent.mapping.sequence = FALSE, handlers = NULL)
                      # }.......
                      
                      e <- new.env(parent = emptyenv())
                      lazyLoad("c:/Users/r2/R/win-library/4.0/yaml/help/yaml", envir = e)
                      # NULL
                      ls(e)
                      # [1] "as.yaml"    "read_yaml"  "write_yaml" "yaml.load" 
                      e$as.yaml
                      # \title{ Convert an R object into a YAML string }\name{as.yaml}\alias{as.yaml}\keyword{ data }\keyword{ manip }\description{
                      #   Convert an R object into a YAML string
                      # }\usage{
                      #   as.yaml(x, line.sep = c("\n", "\r\n", "\r"), indent = 2, omap = FALSE,
                      #           column.major = TRUE, unicode = TRUE, precision = getOption('digits'),
                      #           indent.mapping.sequence = FALSE, handlers = NULL)
                      # }......
                      

                      Rename file as per fixed patter in UNIX

                      copy iconCopydownload iconDownload
                      destfile="$(echo $file | sed -e 's/^APPLE_STORE/APPLE_STORE_${location}/' -e 's/\.csv$/${dtstamp}.csv/')"`
                      mv "$file" "$destfile"
                      
                      #!/bin/bash
                      filelist=./APPLE_STORE_*.csv
                      dtstamp=`date +%Y%m%d%H%M%S`
                      location='NY'
                      
                      for file in ${filelist}
                      do
                      
                        filebase=${file%.csv}
                        part1=`echo ${filebase} | awk -v FS="_" '{print $1}'`
                        part2=`echo ${filebase} | awk -v FS="_" '{print $2}'`
                        part3=`echo ${filebase} | awk -v FS="_" '{print $3}'`
                        mv ${file} ${part1}_${part2}_${location}_${part3}_${dtstamp}.csv
                      
                      done
                      

                      IKScannerDeviceViewDelegate never called

                      copy iconCopydownload iconDownload
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: ICScannerBandData!, scanInfo: [AnyHashable : Any]!, error: Error!)
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: URL!, error: Error!)
                      
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: URL!, fileData: Data!, error: Error!)
                      
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: ICScannerBandData!, scanInfo: [AnyHashable : Any]!, error: Error!)
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: URL!, error: Error!)
                      
                      func scannerDeviceView(IKScannerDeviceView!, didScanTo: URL!, fileData: Data!, error: Error!)
                      

                      awk: cmd. line:1:fatal: division by zero attempted

                      copy iconCopydownload iconDownload
                      awk 'BEGIN{a="";b=1;print b/a}'
                      awk: cmd. line:1: fatal: division by zero attempted
                      
                      awk 'BEGIN{a=0;b=1;print b/a}'
                      awk: cmd. line:1: fatal: division by zero attempted
                      
                      awk 'BEGIN{a="";b=1;print b/a}'
                      awk: cmd. line:1: fatal: division by zero attempted
                      
                      awk 'BEGIN{a=0;b=1;print b/a}'
                      awk: cmd. line:1: fatal: division by zero attempted
                      

                      See all related Code Snippets

                      Community Discussions

                      Trending Discussions on Filebase
                      • postMessage validation failed error occurring during image upload using react-base64
                      • Axios to django-backend post image fail
                      • i Already hosted a Web page Project to Filebase console using firebase deploy comment , How can i Download the Project files Now?
                      • Not Able to post asynchronously in react-redux
                      • dependency and option in meson project
                      • Problem with downloading image and displaying it
                      • uniqid() not generating unique values within a Foreach loop - PHP
                      • Send_email with django generate error _getfullpathname:
                      • Moving files by their filenames
                      • ImageMagick Invalid Image Index
                      Trending Discussions on Filebase

                      QUESTION

                      postMessage validation failed error occurring during image upload using react-base64

                      Asked 2022-Apr-02 at 19:44

                      I am uploading an image and saving it to mongodb but it is showing following error:

                      message: "postMessage validation failed: selectedFile: Cast

                      name: "ValidationError"

                      _message: "postMessage validation failed"

                      I am using react-base64 on the front end side to upload the image.

                      <FileBase type="file" multiple={false} onDone={(base64) => setPostData({ ...postData, selectedFile: base64})} />

                      And i am adding it to DB via fetch :

                      let handleSubmit = (event) => {
                              event.preventDefault();
                              console.log(postData);
                              fetch(`http://localhost:5000/posts/create`, {
                                  method: 'POST',
                                  mode: 'cors',
                                  headers: {
                                      'Content-Type': 'application/json',
                                      // 'Accept': 'application/json'
                                  },
                                  body: JSON.stringify(postData),
                              })
                              .then(response => response.json())
                              .then((dataFromServer) => {
                                  console.info(dataFromServer);
                              })
                              .catch(error => console.error(error));
                      
                          }

                      Can anyone tell me what I am doing wrong and how can i fix this issue

                      ANSWER

                      Answered 2022-Apr-02 at 19:44

                      In the FileBase component, you need to do in this way.

                      You need to destructure the parameter on onDone. In this way onDone={({base64}) => yourFunction()}

                      You can use this one.

                      <FileBase type="file" multiple={false} onDone={({base64}) => setPostData({ ...postData, selectedFile: base64})} />
                      

                      Source https://stackoverflow.com/questions/71720637

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install Filebase

                      Use Composer to install package. Run composer require tmarois/filebase:^1.0. If you do not want to use composer, download the files, and include it within your application, it does not have any dependencies, you will just need to keep it updated with any future releases.

                      Support

                      Anyone can contribute to Filebase. Please do so by posting issues when you've found something that is unexpected or sending a pull request for improvements.

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Reuse Pre-built Kits with Filebase
                      Consider Popular Database Libraries
                      Try Top Libraries by tmarois
                      Compare Database Libraries with Highest Support
                      Compare Database Libraries with Highest Quality
                      Compare Database Libraries with Highest Security
                      Compare Database Libraries with Permissive License
                      Compare Database Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.