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 tag se foloseste pentru a crea o caseta de adaugare text?
<form> <input> <div>
<input type="text" name="a_name" value="val" />
Ce proprietate CSS se foloseste pentru a afisa textul cu majuscule-mici?
display font-variant font-style
h3 {
  font-variant: small-caps;
}
Ce instructiune afiseaza o fereastra cu un mesaj in ea?
for() Date() alert()
var msg = "Viziteaza CoursesWeb.net";
alert(msg);
Indicati codul PHP prin care se obtine IP-ul utilizatorului.
$_SERVER["HTTP_USER_AGENT"] $_SERVER["REMOTE_ADDR"] $_GET[]
$ip = $_SERVER["REMOTE_ADDR"];
echo $ip;
Cum se traduce cuvantul "actually"?
actual de fapt acum
He actually came on time.
- De fapt, el a venit la timp.
Cum se traduce expresia: "Hace buen tiempo"?
Face timp E vreme frumoasa Drum bun
Hoy hace buen tiempo.
- Astazi e vreme frumoasa.
Node.js - Upload fisiere cu Express si Multer

Last accessed pages

  1. Genul substantivelor 2 (7029)
  2. Comenzile tĂș - Imperativul (755)
  3. Caractere speciale - Entitati HTML (13779)
  4. Substantive - Exercitii si teste engleza incepatori (39978)
  5. Coduri pt culori (69628)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (885)
  2. Exercitii engleza - English Tests and exercises - Grammar (390)
  3. Cursuri limba engleza gratuite si lectii online (373)
  4. Coduri pt culori (366)
  5. Gramatica limbii engleze - Prezentare Generala (358)