send-receive-files-in-chat-api

Send and Receive Files and Images in Chat – ChatEngine JavaScript Plugins

In this tutorial, we’ll add file upload and image upload functionality to our ChatEngine chat application using the uploadcare plugin. This allows users to upload any file type directly in chat, whether it be a .png, .doc, or .zip, and send the file to any number of other connected users.

The full GitHub repo for this project is available here.

ChatEngine Setup

First things first, you’ll have to setup ChatEngine via our ChatEngine Quick Start. This enables you to use your own PubNub application keyset and automagically sets up your account to use ChatEngine. It’ll take a couple minutes at most, then you can come back here and continue on.

In this tutorial, we’re going to use the barebones ChatEngine application available in the Quick Start or here. Now, let’s add file sharing functionality!

UploadCare Plugin

First, signup for a free UploadCare account. They’ve got a sandbox tier for development purposes that offers a generous amount of uploads and storage. You’ll need to return to the UploadCare dashboard for your public key in a little bit.

Next, install the uploadcare plugin using:

npm install chat-engine-typing-uploadcare --save

Add reference to the JavaScript file of plugin that we got from npm inside the index.html. Place the below-mentioned line just before the ends.

We will also add the Uploadcare CDN.

<script src="node_modules/chat-engine-typing-indicator/dist/chat-engine-typing-indicator.js"></script>
<script charset="utf-8" src="https://ucarecdn.com/libs/widget/2.10.3/uploadcare.full.min.js"></script>

Inside index.html, we will add HTML element through which one will be able to see what file they uploaded. We will add this just below the chat history.

<div id="output"></div>

We also have to add a hidden element through which the selected files will be uploaded to Uploadcare through their widget.

<input type="hidden" role="uploadcare-uploader" data-crop="disabled" data-images-only="true" />

For the purpose of this example, we’ll send an image file. You can enable any file format upload by making data-images-only as false.

Then go to js/index.js. Here we will add the logic to make the UploadCare plugin work. We need to mention some constants which will be used by the widget:

UPLOADCARE_LOCALE = "en";
UPLOADCARE_TABS = "file url facebook gdrive dropbox instagram evernote flickr skydrive";
UPLOADCARE_PUBLIC_KEY = "Your_UploadCare_Public_Key";
  • UPLOADCARE_LOCALE lets your app know which language to support inside the widget.
  • UPLOADCARE_TABS mentions the upload sources you would like to have.
  • UPLOADCARE_PUBLIC_KEY is you public key which you can get from your Uploadcare account.

Next, we are going to create some variables to refer the UI elements that we will need:

const input = $('#message-to-send');
const widget = uploadcare.Widget('[role=uploadcare-uploader]');
const file = $('#output');

You have to write this inside the ChatEngine ‘on ready’ event:

myChat.plugin(ChatEngineCore.plugin['chat-engine-typing-indicator']());
myChat.uploadcare.bind(widget);
myChat.on('$uploadcare.upload', (payload) => {
let text = `<img src="${payload.data.cdnUrl}" style="width: 350px;"/>`
$('#output').append(text)
});

This will bring in the Uploadcare plugin and bind it to your chat room instance, which is myChat here.

As soon as any file is uploaded and ‘$uploadcare.upload’ event is fired, the callback function receives a payload. We retrieve the remote URL of uploaded image and put it in a HTML image tag, and put it in the div#output as a preview (more documentation here).

Now, we have to handle the case where a user can just send the image or send the image with accompanying text.

In sendMessage function, we put this:

let message = $('#message-to-send').val().trim();
    let finalMessage

    if (file.is(':empty')){
        finalMessage = message
    } else {
        finalMessage = file.html() + '<br>' + message
    }

We get the text message by default. Then we check if there is any content inside div#output, as it could have something from the previous step. If it does, we create a final message of image plus text, otherwise just text. And send this final message in the emit event.

And on sending it, we empty the contents inside the div using file.html(”);

Since the plugin will create some HTML, we need to do HTML escaping while rendering these messages, otherwise we will see messages in raw HTML format, which we don’t want.

In order to do that, back in index.html, we have to make one modification. Change {{messageOutput}} to {{{messageOutput}}}. This is how you escape HTML in Handlebars JS.

Wrapping Up

Hoorah! Users can now upload any file format (documents, PDFs, images, videos etc) from any source (Dropbox, Google Drive, Local system etc), add a message to it, send it and view it later on too.

With ChatEngine, you can add a ton of other powerful plugins, like typing indicators, emojis, and markdown rendering, to build out the chat functionality. You can find all the plugins and how to implement them here.

Use Cases:

Try PubNub Today

Share this on facebookShare this on TwitterShare this on Linkedin