Sending Images via SMS with Filepicker and Twilio

If you are a web developer, you know that handling file uploads is not fun. You are either spending time dealing with files and permissions, or learning how your language handles MIME multipart encoding. Then there is the problem of dealing with large file uploads and cross-browser compatibility.

Even when you get the basics figured out, all that you have working is something that allows your users to upload files from their computer. If you want to enable your users to choose photos and files from a service like Facebook, Dropbox, Google Drive or Flickr, well, that’s a whole other story. Integrating these different APIs, normalizing response formats, and maintaining these integrations can be time consuming.

Does this sound familiar? If it does, you will be excited to learn that Filepicker.io has made this process a whole lot easier. Filepicker.io provides APIs to connect, process, and store any piece of content in your web application. For example if you are building an application that needs to send files or photos to your users via SMS, then you can use Filepicker.io with Twilio to make this happen. Let’s explore how to build this.

With Filepicker.io, here is the bare minimum HTML that you will need to write to enable someone to send a link to an image via SMS:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<!DOCTYPE html>

<html lang="en">

<head><title>SMS an image</title></head>

<body>

<form action="/"method="POST">

Cell phone number:<input name="phone_number"type="text"/>

Image tosend via SMS:<input name="file"type="filepicker"/>

<button type="submit">SendFile</button>

</form>

<script src="http://api.filepicker.io/v1/filepicker.js"></script>

<script type="text/javascript">

filepicker.setKey('{{ filepicker_api_key }}');

</script>

</body>

</html>

As you look over the HTML, pay special attention to the <input name="file" type="filepicker" /> tag and the two <script> tags at the bottom.

When a browser loads this HTML, the Filepicker script will turn any the <input> tag with a type="filepicker" attribute into a special file picking “widget” that opens this dialog when clicked:

After someone has used the Filepicker.io dialog to select an image, a URL to that image is inserted into the value of the <input> tag. That URL is what will be submitted as part of the HTTP POST request that will be made when the “Send File” button is clicked.

So far, all that we have is some HTML that will submit a phone number and URL via a POST request. To actually send the message we will need a little bit of server side logic to take the URL and send the SMS to the phone number. For this, we will be using Python with the Flask web development framework. Here is a simple Flask application that will do just that:

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

importos

fromtwilio.rest importTwilioRestClient

fromflask importFlask,request,render_template

twilio_account_sid=''

twilio_auth_token=''

twilio_from_number=''

filepicker_api_key=''

app=Flask(__name__)

client=TwilioRestClient(twilio_account_sid,twilio_auth_token)

@app.route("/",methods=['POST','GET'])

defindex():

ifrequest.method=='POST':

client.sms.messages.create(

to=request.form['phone_number'],

from_=twilio_from_number,

body="Check this out: %s?dl=false"%request.form['file'])

fp_key=filepicker_api_key

returnrender_template('simple.html',filepicker_api_key=fp_key)

if__name__=="__main__":

port=int(os.environ.get('PORT',5000))

app.debug=True

app.run(host='0.0.0.0',port=port)

If you want to run the code above, here is what you’ll need to do:

Save the Python code in a file named “app.py”.

Create a directory named “templates” in the same directory as the “app.py” file.

Save the HTML in a file named “simple.html” in the “templates” directory.

Run “pip install Flask“

Run “pip install twilio“

Run “python app.py“

Open http://localhost:5000/ in your web browser of choice.

At this point, we have a very basic looking application. It works, but doesn’t look great. Let’s fix that by adding some design from Twitter Bootstrap and a little bit of error handling.

For the design, Twitter Bootstrap comes with CSS for a very nice looking “Horizontal form“. It looks nice, but requires a pretty substantial change to our HTML. For this we will start by modifying the Bootstrap “starter template“, remove the “navbar” and then enter the following HTML into the <body> tag:

Next, lets add some more HTML to let us know if there was an issue sending the SMS or to show us that the SMS was sent successfully. To only show the messages when appropriate, we will use the conditional blocks from the Jinja2 tempting language that Flask uses. Here is what those look like:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

{%ifsms_sentissameasFalse%}

<div class="row-fluid">

<div class="span4">

<h3 class="text-error">Error sending SMS. Try again?</h3>

</div>

</div>

{% endif %}

{% if sms_sent is sameas True %}

<div class="row-fluid">

<div class="span4">

<h2>Sent to {{ phone_number }}:</h2>

<img src="{{ file }}"/>

</div>

</div>

{%endif%}

And finally, we will update our backend code to take advantage of those changes. Here are the updates that we will make:

# TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables must be set

client=TwilioRestClient()

@app.route("/",methods=['POST','GET'])

defindex():

option={}

option['filepicker_api_key']=os.environ.get('FILEPICKER_API_KEY')

ifrequest.method=='POST':

option['file']=request.form['file']

option['phone_number']=request.form['phone_number']

try:

from_=os.environ.get('TWILIO_FROM_NUMBER')

body="Check out this picture: %s?dl=false"%option['file']

client.sms.messages.create(to=option['phone_number'],

from_=from_,

body=body)

option['sms_sent']=True

except:

option['sms_sent']=False

returnrender_template('index.html',**option)

if__name__=="__main__":

port=int(os.environ.get('PORT',5000))

app.run(host='0.0.0.0',port=port)

After these changes, we’ve got quite a bit more code, but the page we render looks much nicer:

Here is what the page will look like after picking a file and clicking the “Send File” button. You can see that one of the conditional templates has been activated and is showing us what image we just sent and who we sent the image URL to:

Want to try this code out for yourself? Here are the commands that you’ll need to run:

Get this information from your Twilio account. If you don’t have one already, sign up for a Twilio account here.
You will find the values for your “Account SID” and “Auth Token” in your Twilio account here: https://www.twilio.com/user/account
Set “TWILIO_FROM_NUMBER” to any Twilio number you own, you can see a list of what numbers you own here: https://www.twilio.com/user/account/phone-numbers/incoming

heroku config:add FILEPICKER_API_KEY="{{ your filepicker api key}}"

This is your Filepicker API key. If you don’t have a Filepicker account yet. If you don’t have one already, sign up for a Filepicker account here.
You will find your Filepicker API key here: https://developers.filepicker.io/home/

heroku config

Make sure it’s all the settings are correct!

git push heroku master

heroku open

The last command will open your web browser. The browser will load the address where Heroku is hosting the SMS application we have been building. Once you’re looking at the application, here is what you’ll need to do to send yourself a link to an image:

Enter in your cellphone number.

Click the “Pick File” button and upload an image.

Click “Send File” button.

A few seconds after you click the “Send File” button, you will receive an SMS with a URL for the image you just uploaded.

This is a simple demo, but I hope that I’ve given you a taste of the cool things you can do with Filepicker, Twilio, and about 93 lines of code.

What other cool things can you think of that can be built with Filepicker.io and Twilio?