PRO: Upload and send Data to API

Your Challenge:
Offer a HTML-Form to your user for inserting some text and uploading a mediafile. The mediafile should be stored locally and displayed together with the text input. Also the text and mediafile should be sent to an API.


This is the way to achieve this:

Create two JCI-Templates.
JCI-Template 1:

  • templatename: uploadaddpic
  • URL: This must be a real API where you want to send the data (“dummyrequest” is not ok here)
  • method: CURL-POST
  • urlparam4twig: text1
  • twig-Template:
{{_context | json_encode }}

JCI-Template 2:

  • templatename: uploadmediafile
  • URL: URL to an API which gives all data you sent via this form. If not needed use “dummyrequest”.
  • method: CURL-POST
  • twig-template:
    get_data_of_uploaded_file: This JCI-twig-function returns $_FILES, a ‘superglobal’ PHP-variable where the HTTP File Upload variables are stored.
{% if urlparam.text1 %}
input text: {{urlparam.text1}}<br>
{% set picdata = get_data_of_uploaded_file('yourmediafile') %}
data of uploaded file: {{picdata | json_encode}}<hr>
{% set maxsizekb= 2*1024*1024 %}
{% if picdata.error==0 and picdata.size<maxsizekb %}
upload file is ok for saving in wp-medialib<br>
{% set jciaddkond='{"answer":"hello","urlparam":{"text1":""},"apiresponseinfo":[]}' %}
shortcode for saving file: {{jciaddkond}}<hr>
{% set execsh = jciaddkond | doshortcode %}
shortcode-execution result: {{execsh | dump }}<br>
{% set execshArr = execsh | json_decode %}
{% set uploadedImgInWPLib = execshArr.apiresponseinfo.upload.attachment_url %}
<hr>{{urlparam.text1}}<br><img src="{{uploadedImgInWPLib }}">
{% else %}
mediafile not stored:<br>
picdata.error: {{picdata.error}}<br>
maxsize:  {{(maxsizekb/1024)| round(2)}} kB<br>
Bildgröße: {{(kondpicdata.size/1024)| round(2)}} kB<br>
{% endif %}
{% endif %}
 
<form action=/upload/ enctype="multipart/form-data" method=POST>
<input type=text name=text1 placeholder="Your example text">
<input type="file" name="yourmediafile">
<input type=submit>
</form>
  • urlparam4twig:
text1##yourmediafile

Use the JCI-Templates:

Place the following sortcode on the Page /upload/ (see <from action=…>” at twig-template JCI-Template 2, change this if needed)

[[jsoncontentimporterpro nameoftemplate="uploadmediafile" orderofshortcodeeval=10]] 

In Action, to avoid unwanted uploads this page is password protected:
https://api.json-content-importer.com/upload/

Ok, if you need a nice free plugin out of the box: Check https://wordpress.org/plugins/wp-file-upload/