0

I am new to loopback and i have a form where have the some fields with file upload. now i am able to store the field values using the PersistedModel with mysql database.

I want to save the file upload also in some location.how to do this can anyone explain with example. I have seen the loopback 3 storage documentation, but i couldn't get. I am using the dropzone js for file upload. Here is my code

<form  id="myForm" novalidate>
   <div class="form-row">
      <div class="form-group col-md-6">
         <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First Name" required>
      </div>
   </div>
   <div class="form-row">
      <div class="form-group col-md-6">
         <input type="email" class="form-control" id="email" name="email" placeholder="example@gmail.com" required>
         <div class="invalid-feedback">Please Enter a Valid Email Id.</div>
      </div>
      <div class="form-group col-md-6">
         <input type="text" id="role" name="role" class="form-control" placeholder="Job Role" >
      </div>
   </div>
   <div class="form-row">
      <div class="form-group col-md-12">
         <textarea class="form-control" id="message" name="message" placeholder="Message" required></textarea>
      </div>
   </div>
   <div id="resume" class="dropzone form-control"></div>
   <input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
</form>

SCRIPT

<script type='text/javascript'>
   $("#myForm").submit(function(e) {
      e.preventDefault();
      var parms = {
   firstname : $("#firstname").val(),
   email : $("#email").val(),
   role : $("#role").val(),
   message: $("#message").val()
   };
   $.ajax({
   method: 'POST',
   url:  "http://localhost:3000/api/careers",
   async: false,
   dataType : "json",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify(parms),
   success: function(data){
   console.log('Submission was successful.');
   // location.reload();
   console.log(data);
   }, error: function (data) {
      console.log('An error occurred.');
      console.log(data);
         },   
      })
   });
</script>
Googlian
  • 6,077
  • 3
  • 38
  • 44
Sam
  • 1,381
  • 4
  • 30
  • 70
  • Do you want to upload a file with text fields and store them into database also the same time store the file into some path in your directory right ? Do you want to use AJAX or normal uploading method in PHP/NodeJS ? – Googlian Mar 07 '19 at 04:54
  • @Googlian yes i want to store the field values and the file – Sam Mar 07 '19 at 04:58
  • in PHP or NodeJS ? – Googlian Mar 07 '19 at 04:59
  • NodeJS am using only loopback 3 for backend – Sam Mar 07 '19 at 05:03
  • What is your backend code ? Can you put the back-end sample code – Googlian Mar 07 '19 at 05:07
  • loopback model { "name": "career","base": "PersistedModel","idInjection": true,"options": {"validateUpsert": true }, "properties": { "id": { "type": "number" },"firstname": {"type": "string","required": true },"email": {"type": "string","required": true},"role": {"type": "string","required": true}, "message": {"type": "string","required": true },"resume": {"type": "string"} }, "validations": [], "relations": {},"acls": [],"methods": {} } – Sam Mar 07 '19 at 05:11
  • Did you refer https://loopback.io/doc/en/lb2/Storage-component.html – Googlian Mar 07 '19 at 05:16
  • yes am using loopback3 – Sam Mar 07 '19 at 05:17
  • for upload can you use express with multer – Googlian Mar 07 '19 at 05:24
  • how to use can u pls give me an example – Sam Mar 07 '19 at 05:30

2 Answers2

0

Use express.js with multer to easily upload files and insert database.

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

Install express and multer

npm install --save multer
npm install --save express

app.js in back-end

const express = require('express')
const path = require('path')
const multer = require('multer');

const port = 3000

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

const upload = multer({ storage: storage })
const app = express()

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'))
})

app.post('/upload', upload.single('avatar'), function (req, res, next) {

    var fileName = req.file.originalname

    // Do your database operations here
    console.log(fileName)

    res.send(req.file)
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

index.html in front-end

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="avatar" />
    <input type="submit" value="Upload">
</form>
Googlian
  • 6,077
  • 3
  • 38
  • 44
0

I also have a similar implementation check this out

However, you need to specify the storage container you are using in the datasources.json file Here's My implementation of the storage connector.

localstorage: {
    "name": "localstorage",
    "connector": "loopback-component-storage",
    "provider": "filesystem",
    "root": "./files/",
    "nameConflict": "makeUnique",
    "maxFileSize": "104857600"
}

and in model-config.json add this:

"Container": {
    "dataSource": "localstorage",
    "public": true
},

also don't forget to add Container.json in common/models folder which would look like this:

{
   "name": "Container",
   "base": "Model"
}

Now you will be able to post the files to "/api/container" path