Curs Javascript

- Screenshoot-uri
- Pe scurt despre upload.js

Exista un modul bun pentru a face upload de fisiere, numit "Multer".
Bazat pe modulul Multer, am creat o clasa JavaScript pentru a uploada cu usurinta fisiere cu node.js, cu un minim de cod necesar.
Aceasta clasa, numita uploadFile este exportata ca un modul si poate fi inclusa cu require().

Creare unui modul Node.js pentru a uploada fisiere cu Multer

• Puteti crea fisierele necesare cu codul prezentat in aceasta pagina, sau..:
- Click pe acest link pentru a descarca tot script-ul: Node.js Upload Fisiere.

1. Mai intai, trebuie sa instalam modulele Express si Multer cu NPM (Node.js Package Manager).
Deschide interfata command line si spuneti aplicatiei NPM sa descarce aceste pachete.
npm install --save express

npm install --save multer
2. Acum sa cream modulul pentru upload de fisiere, cu optiuni pentru extensiile de fisiere permise si marimea maxima a fisierului ce poate fi incarcat pe server.
In directorul proiectului tau Node.js, creaza un fisier numit "upload.js" si adauga acest cod (click pe cod pentru a-l selecta):
//uploads file to server with multer module
class uploadFile {
  //set needed properties
  constructor(){
    this.multer = require('multer');
    this.destination = null;
    this.exts =['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt']; //allowed extensions
    this.maxsize =3; //maximum allowed file size; in MB
    this.rewrite = true; //true=rewrite the file if exists; false=sets the file name: 'originalname-Date.now()'
    this.init();
  }

/*Sets properties, receives object:
 {
  destination: 'folder for uploaded file' (Required, default: null)
  exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
  maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3)
  rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: 'originalname-timestamp'
 }
*/
  set setProp(o){
    if(o.destination) this.destination = o.destination;
    if(o.exts) this.exts = o.exts;
    if(o.maxsize) this.maxsize = o.maxsize*1;
    if(o.rewrite) this.rewrite = o.rewrite;
  }

  //set main multer objects for upload
  init(){
    //sets destination folder and file name
    var storage = this.multer.diskStorage({
      destination: (req, file, cb)=>{
        cb(null, this.destination);
      },
      filename: (req, file, cb)=>{
        this.er_ext ='No valid extension.\n Allowed extensions: '+ this.exts.join(', ');
        //check extension
        var ext = file.originalname.match(/\.([A-z0-9]+)$/i);
        if(ext && ext[1]){
          ext = ext[1];
          for(var i=0; i<this.exts.length; i++){
            if(this.exts[i]==ext){
              this.er_ext ='';
              break;
            }
          }
        }

        //if no error, sets destination file name
        if(this.er_ext==''){
          if(this.rewrite ===true) var fname = file.originalname;
          else var fname = file.originalname.replace('.'+ext, '-'+Date.now()+'.'+ext);
          cb(null, fname);
        }
        else return cb(new Error(this.er_ext), false);
      }
    });
    //Acepts a single file with the name 'up_f'. This file will be stored in req.file
    this.upload = this.multer({storage: storage, limits:{ fileSize: this.maxsize*1024*1024 }}).single('up_f');

  }

  //Posting the file upload; Receives - req=request, res=response, cb=callback function
  //Returns an object in the callback function, with file data, or {err:'error message'} in case of error
  post(req, res, cb){
    if(this.destination ==null) return cb({err:"Set a destination folder for upload, with: dirUpload \n Example:\n upload.dirUpload = __dirname+'/uploads'"});
    else {
      // req.file is the `avatar` file; req.body will hold the text fields, if there were any 
      this.upload(req, res, (err)=>{
        if(err){
          if(this.er_ext !='') var re ={err:this.er_ext};
          else if(err.code =='LIMIT_FILE_SIZE') var re ={err:'File to large, maximum allowed size: '+ this.maxsize +' MB'};
          else var re ={err:err};
        }
        else {
          var re = req.file;
          console.log('File Uploaded');
        }

        return cb(re);
      });
    }
  }
}

//assign object of uploadFile class to module.exports
module.exports = new uploadFile();
3. Acum vom crea un fisier ".htm" cu formularul de upload si codul Ajax care efectuaza upload-ul fara a reincarca pagina.
Salveaza urmatorul cod intr-un fisier numit "form.htm", in acelasi director:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Node.js Upload Files</title>
</head>
<body>
<h1>Node.js Upload Files</h1>
<pre id="resp">Here it shows server response</pre>
<form id="uploadf" enctype="multipart/form-data" action="/upload" method="post">
 <input type="file" name="up_f" id="up_f" />
 <input type="submit" value="Upload" name="submit" />
</form>
<script>
var resp = document.getElementById('resp');
var form = document.getElementById('uploadf'); //get the form

//sends form data with ajax to server
function sendFile(ev){
  ev.preventDefault();

  //get the form and send its data to server
  var data = new FormData(form);
  var req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  req.open('post', form.action, true);
  req.send(data);

  //receives and parse response in JSON format
  req.onreadystatechange=function(){
    if(req.readyState ==4){
      var obr = JSON.parse(req.responseText.replace(/\\\\/g, '/'));
      if(obr){
        //HERE you can parse the obr JSON object

        if(obr.err) resp.innerHTML ='<h4 style="color:#ee0000">'+JSON.stringify(obr.err, null, 2).replace(/(^")|("$)/g, '').replace(/\\n/ig, '<br>')+'</h4>';
        else resp.innerHTML = JSON.stringify(obr, null, 2);
      }
    }
  };
  return false;
}

// calls sendFile() on submit
form.addEventListener('submit', sendFile, false);
</script>
</body>
</html>
- Codul Javascript din fisierul "form.htm" trimite formularul catre server si afiseaza raspunsul in pagina web.

4. Acum, vom crea un fisier "server.js" care foloseste Express pentru a afisa paginile in browser si modulul "upload.js" pentru a uploada fisierul cand formularul este trimis.
Copiaza si salveaza urmatorul cod intr-un fisier "server.js" in acelasi director:
const express = require('express');
const upload = require('./upload.js');
const port =8080;
const app = express();
app.set('port', port); 

//Showing form.htm file on homepage
app.get('/', (req, res)=>{
  res.sendFile(__dirname+'/form.htm');
});

/*
Before upload.post(), calls setProp() passing an object, to set destination folder (here 'uploads'), and other properties
Full object:
 {
  destination: 'folder for uploaded file' (Required, default: null)
  exts: [array with allowed extensions] (Optional, default: ['bmp', 'doc', 'flv', 'gif', 'jpg', 'jpe', 'json', 'mp3', 'mp4', 'pdf', 'png', 'txt'])
  maxsize: integer number for maximum allowed file size, in MB (Optional, default: 3); 0.5 = 500 KB
  rewrite: true or false (Optional, default: true); true=rewrite the file if exists; false=sets the file name: 'originalname-Date.now()'
 }
*/
upload.setProp ={destination: __dirname+'/uploads', exts:['jpg', 'png', 'mp3'], maxsize:0.5};

//calls upload.post() when POST request
app.post('/upload', (req, res)=>{
 //passes a callback function that receives an object with response: data of the uploaded file, or {err:'error message'} in case of error
  upload.post(req, res, (re)=>{
    //HERE you can parse the received object

    //outputs the object response as a JSON string
    res.end(JSON.stringify(re));
  });
});

var server = app.listen(port, ()=>{
  console.log('Listening on port ' + server.address().port);
});
- Initiaza "server.js" in interfata command line.
node test/server.js
Acceseaza serverul in browserul tau, prin portul 8080 ( //localhost:8080/ ).
- Acum poti incarca fisiere pe server cu Node.js.

• Dupa ce fisierul este incarcat, metoda post() a modulului "upload.js" returneaza un obiect cu datele fisierului, intr-o functie "callback' transmisa ca argument:
{
  "fieldname": "up_f",
  "originalname": "dolphin.jpg",
  "encoding": "7bit",
  "mimetype": "image/jpeg",
  "destination": "e:/nodejs/test_upload/uploads",
  "filename": "dolphin.jpg",
  "path": "e:/nodejs/test_upload/uploads/dolphin.jpg",
  "size": 3752
}
- sau un obiect cu mesajul de eroare, in caz de eroare: "{err:'error message'}"

Screenshoot-uri

Fisierele pentru serverul Node.js si modulul upload.js, intr-un director "test:
Node.js upload test project

Obiectul rezultat cu datele fisierului incarcat:
Node.js response upload file

Mesaj in caz de eroare:
Node.js upload test project

Pe scurt despre upload.js

upload.js este un modul care simplifica codul pentru incarcare fisiere pe server cu node.js. Este bazat pe modulul Multer.

- Pentru a descarca scriptul, click pe: Node.js Upload Fisiere

Folosire:

1. Instaleaza modulul multer cu NPM din interfata command line:
npm install --save multer
2. Copiaza "upload.js" si "form.htm" direct in directorul proiectului tau.
3. Include "upload.js" in fisierul pt. serverul Node.js:
const = require('./upload.js');
4. Seteaza destinatia directorului pentru upload, cu upload.setProp :
upload.setProp ={destination: __dirname+'/uploads'};
- In plus, puteti seta si alte proprietati: "exts", "maxsize", "rewrite" (vezi comentariile din fisierul upload.js).

5. Afisati continutul fisierului "form.htm" in browser. Exemplu cu Express:
res.sendFile(__dirname+'/form.htm');
6. Apelati metoda upload.post() cand date de formular sunt trimise prin POST:
upload.post(req, res, callback);
"callback" este o functie apelata recursiv, cu un argument ce va contine un obiect cu datele fisierului incarcat.

• Mai important :
- Aveti o viata buna cu toata lumea si cu voi insiva.

Un Test simplu in fiecare zi

HTML
CSS
JavaScript
PHP-MySQL
Engleza
Spaniola
Ce tip de <input> creaza o paleta de culori pentru selectare culoare?
type="text" type="color" type="date"
<input type="color" name="get_color" />
Care metoda CSS roteste elementul HTML la un anumit numar de grade?
scale() translate() rotate()
#some_id:hover {
  transform: rotate(60deg);
  -ms-transform: rotate(60deg);    /* IE 9 */
  -moz-transform: rotate(60deg);   /* Firefox */
}
Click pe functia care returneaza numarul cel mai mare.
pow() min() max()
var maxn = Math.max(8, 4, 88, 56);
alert(maxn);      // 88
Ce functie previne ca un fisier sa fie inclus mai mult de o data intr-o pagina?
include() include_once() require()
include_once("un_fisier.php");
Care este traducerea corecta pentru: "Ahead of time"?
Peste timp La timp Inainte de vreme
Most people arrived ahead of time.
- Cei mai multi oameni au sosit inainte de vreme (prea devreme).
Indicati traducerea corecta a cuvantului "buenĂ­simo"
mai bun mai putin bun extrem de bun
Este fruto es buenĂ­simo.
- Acest fruct este extrem /nemaipomenit de bun.
Node.js - Upload fisiere cu Express si Multer

Last accessed pages

  1. OOP - Constante, Proprietati si Metode Statice (3812)
  2. Node.js - Lectia de inceput, instalare (1919)
  3. Subjunctiv 3 (1245)
  4. Confusable words - Cuvinte confundabile (6139)
  5. Prezentul simplu - Exercitii si teste incepatori (67614)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (411)
  2. Gramatica limbii engleze - Prezentare Generala (395)
  3. Prezentul simplu si continuu - Present Tense Simple and Continuous (368)
  4. Exercitii engleza - English Tests and exercises - Grammar (304)
  5. Prezentul simplu - Exercitii si teste incepatori (263)