Image Upload | Node.JS – Froala

Image Upload

The following sections describe how to handle image uploads on your server using Node.JS as a server-side language. For information on the upload workflow refer to the image upload documentation.

Dependencies

The node.JS image upload example requires the following dependencies:

  • Using npm you need package.json
  • Using bower you need bower.json

Make sure that you run npm install, or if you are using bower run bower install

Frontend

Setting up the index page.

  1. On the head section include the Editor style.
  2.  
      

    <

    html

    >

    <

    head

    >

    <

    meta

    charset

    =

    "utf-8"

    >

    link

    href

    =

    "https://cdn.jsdelivr.net/npm/ [email protected] /css/froala_editor.pkgd.min.css"

    rel

    =

    "stylesheet"

    type

    =

    "text/css"

    />

    />

    </

    head

    >
  3. On the body section include the Editor JS files and define the area for the editor.
  4.   

    <

    body

    >

    script

    type

    =

    "text/javascript"

    src

    =

    "https://cdn.jsdelivr.net/npm/ [email protected] /js/froala_editor.pkgd.min.js"

    </

    script

    >

    <

    div

    class

    =

    "sample"

    >

    <

    h2

    >image upload example.

    </

    h2

    >

    <

    form

    >

    <

    textarea

    id

    =

    "edit"

    name

    =

    "content"

    >

    </

    textarea

    >

    </

    form

    >

    </

    div

    >
  5. Initialize the editor and set the image upload URL
  6.   

    <

    script

    >

    new

    FroalaEditor(

    '#edit'

    , { imageUploadURL:

    '/UploadFiles'

    ,

    imageUploadParams

    : {

    id

    :

    'my_editor'

    } })

    </

    script

    >

    </

    body

    >

    </

    html

    >

The full code should look like this:

 
  

<

html

>

<

head

>

<

meta

charset

=

"utf-8"

>

link

href

=

"https://cdn.jsdelivr.net/npm/ [email protected] /css/froala_editor.pkgd.min.css"

rel

=

"stylesheet"

type

=

"text/css"

/>

/>

</

head

>

<

body

>

script

type

=

"text/javascript"

src

=

"https://cdn.jsdelivr.net/npm/ [email protected] /js/froala_editor.pkgd.min.js"

</

script

>

<

div

class

=

"sample"

>

<

h2

>image upload example.

</

h2

>

<

form

>

<

textarea

id

=

"edit"

name

=

"content"

>

</

textarea

>

</

form

>

</

div

>

<

script

>

new

FroalaEditor(

'#edit'

, { imageUploadURL:

'/UploadFiles'

,

imageUploadParams

: {

id

:

'my_editor'

} })

</

script

>

</

body

>

</

html

>

The full code should look like this:

 
    

<

html

>

<

head

>

<

meta

charset

=

"utf-8"

>

link

href

=

"https://cdn.jsdelivr.net/npm/ [email protected] /css/froala_editor.pkgd.min.css"

rel

=

"stylesheet"

type

=

"text/css"

/>

/>

</

head

>

<

body

>

script

type

=

"text/javascript"

src

=

"https://cdn.jsdelivr.net/npm/ [email protected] /js/froala_editor.pkgd.min.js"

</

script

>

<

div

class

=

"sample"

>

<

h2

>Image upload example.

</

h2

>

<

form

>

<

textarea

id

=

"edit"

name

=

"content"

>

</

textarea

>

</

form

>

</

div

>

<

script

>

new

FroalaEditor(

'#edit'

, { imageUploadURL:

'/UploadFiles'

,

fileUploadParams

: {

id

:

'my_editor'

} })

</

script

>

</

body

>

</

html

>

Backend

server.js handles the server part for Node.JS

server.js handles both image and file upload

 
  

var

express =

require

(

"express"

);

var

app = express();

var

bodyParser =

require

(

"body-parser"

)

var

path =

require

(

"path"

);

var

fs =

require

(

"fs"

);

var

upload_file =

require

(

"./file_upload.js"

);

var

upload_image =

require

(

"./image_upload.js"

); app.use(express.static(__dirname +

"/"

)); app.use(bodyParser.urlencoded({

extended

:

false

})); app.get(

"/"

,

function

(

req, res

) { res.sendFile(__dirname +

"/index.html"

); }); app.post(

"/file_upload"

,

function

(

req, res

) { upload_file(req,

function

(

err, data

) {

if

(err) {

return

res.status(

404

).end(

JSON

.stringify(err)); } res.send(data); }); }); app.post(

"/image_upload"

,

function

(

req, res

) { upload_image(req,

function

(

err, data

) {

if

(err) {

return

res.status(

404

).end(

JSON

.stringify(err)); } res.send(data); }); });

var

filesDir = path.join(path.dirname(

require

.main.filename),

"uploads"

);

if

(!fs.existsSync(filesDir)){ fs.mkdirSync(filesDir); } app.listen(

3000

,

function

(

) {

console

.log(

"Example app listening on port 3000!"

); });

image_upload.js handles the upload part. It has basic image format validations that can be easily extended.

The uploads directory must be set to a valid location before making uploads. The path can be any folder that is accessible and writable.

If the uploaded image passes the validation step, the server responds with a JSON object containing a link to the uploaded file.

E.g.: {"link":"http://server_address/uploads/name_of_file"}

var

Busboy =

require

(

"busboy"

);

var

path =

require

(

"path"

);

var

fs =

require

(

"fs"

);

var

sha1 =

require

(

"sha1"

);

function

getExtension

(

filename

) {

return

filename.split(

"."

).pop(); }

function

isImageValid

(

filename, mimetype

) {

var

allowedExts = [

"gif"

,

"jpeg"

,

"jpg"

,

"png"

,

"svg"

,

"blob"

];

var

allowedMimeTypes = [

"image/gif"

,

"image/jpeg"

,

"image/pjpeg"

,

"image/x-png"

,

"image/png"

,

"image/svg+xml"

];

var

extension = getExtension(filename);

return

allowedExts.indexOf(extension.toLowerCase()) !=

-1

&& allowedMimeTypes.indexOf(mimetype) !=

-1

; }

function

upload

(

req, callback

) {

var

fileRoute =

"/uploads/"

;

var

saveToPath =

null

;

var

hadStreamError =

null

;

var

link =

null

;

function

handleStreamError

(

error

) {

if

(hadStreamError) {

return

; } hadStreamError = error;

if

(saveToPath) {

return

fs.unlink(saveToPath,

function

(

err

) {

return

callback(error); }); }

return

callback(error); }

try

{

var

busboy =

new

Busboy({

headers

: req.headers }); }

catch

(e) {

return

callback(e); } busboy.on(

"file"

,

function

(

fieldname, file, filename, encoding, mimetype

) {

if

(

"file"

!= fieldname) { file.resume();

return

callback(

"Fieldname is not correct. It must be "

file

"."

); }

var

randomName = sha1(

new

Date

().getTime()) +

"."

+ getExtension(filename); link = fileRoute + randomName;

var

appDir = path.dirname(

require

.main.filename); saveToPath = path.join(appDir, link); file.on(

"error"

, handleStreamError);

var

diskWriterStream = fs.createWriteStream(saveToPath); diskWriterStream.on(

"error"

, handleStreamError); diskWriterStream.on(

"finish"

,

function

(

) {

var

status = isImageValid(saveToPath, mimetype);

if

(!status) {

return

handleStreamError(

"File does not meet the validation."

); }

return

callback(

null

, {

link

: link}); }); file.pipe(diskWriterStream); }); busboy.on(

"error"

, handleStreamError); req.on(

"error"

, handleStreamError);

return

req.pipe(busboy); }

module

.exports = upload;