title: Redactor (Wysiwyg editor) / Images Upload / Classic ASP / JSON
body: <p>Right, after years working with various wysiwyg editor, i'm actual thinking of purchasing the imperavi's redactor wysiwyg editor (<a href="http://imperavi.com/redactor/" rel="nofollow noreferrer">http://imperavi.com/redactor/</a>), however i'm trying to fiddle about with the trail version and Classic ASP in order to use the image/file upload functionality of the script, Currently the image/file upload functions are written in PHP/JSON, and would love to rewrtie them into Classic ASP.</p>
  
  <p>I will try to post the code as much as possible below:</p>
  
  <p><strong>HTML FORM WITH REDACTOR WYSIYWG</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;  
      &lt;title&gt;All uploads&lt;/title&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;link rel="stylesheet" type="text/css" href="../css/style.css" /&gt;       
      &lt;link rel="stylesheet" href="../redactor/redactor.css" /&gt;
      &lt;script type="text/javascript" src="../lib/jquery-1.8.2.min.js"&gt;&lt;/script&gt;   
      &lt;script src="../redactor/redactor.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
      $(document).ready(
          function()
          {
              $('#redactor_content').redactor({   
                  imageUpload: '../demo/scripts/image_upload.php',
                  fileUpload: '../demo/scripts/file_upload.php',
                  imageGetJson: '../demo/json/data.json'
              });
          }
      );
      &lt;/script&gt;               
  &lt;/head&gt;
  
  &lt;body&gt;
      &lt;div id="page"&gt;
      &lt;textarea id="redactor_content" name="content"&gt;
          &lt;h2&gt;Hello and Welcome&lt;/h2&gt;
          &lt;p&gt;I never did quite grasp him, though he endeavored to explain it to me upon numerous occasions.  I suggested telepathy, but he said no, that it was not telepathy since they could only communicate when in each others' presence, nor could they talk with the Sagoths or the other inhabitants of Pellucidar by the same method they used to converse with one another.&lt;/p&gt;
          &lt;p&gt;"What they do," said Perry, "is to project their thoughts into the fourth dimension, when they become appreciable to the sixth sense of their listener.  Do I make myself quite clear?"&lt;/p&gt;
          &lt;p&gt;"You do not, Perry," I replied.  He shook his head in despair, and returned to his work.  They had set us to carrying a great accumulation of Maharan literature from one apartment to another, and there arranging it upon shelves.  I suggested to Perry that we were in the public library of Phutra, but later, as he commenced to discover the key to their written language, he assured me that we were handling the ancient archives of the race.&lt;/p&gt;
          &lt;p&gt;During this period my thoughts were continually upon Dian the Beautiful.  I was, of course, glad that she had escaped the Mahars, and the fate that had been suggested by the Sagoth who had threatened to purchase her upon our arrival at Phutra.  I often wondered if the little party of fugitives had been overtaken by the guards who had returned to search for them.  Sometimes I was not so sure but that I should have been more contented to know that Dian was here in Phutra, than to think of her at the mercy of Hooja the Sly One.  Ghak, Perry, and I often talked together of possible escape, but the Sarian was so steeped in his lifelong belief that no one could escape from the Mahars except by a miracle, that he was not much aid to usâ€”his attitude was of one who waits for the miracle to come to him.&lt;/p&gt;   
      &lt;/textarea&gt; 
      &lt;/div&gt;                      
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>PHP IMAGE UPLOAD SCRIPT</strong> - (imageUpload: '../demo/scripts/image_upload.php')</p>
  
  <pre><code>&lt;?php
  
  // This is a simplified example, which doesn't cover security of uploaded images. 
  // This example just demonstrate the logic behind the process. 
  
  
  // files storage folder
  $dir = '/home/web/sitecom/images/';
  
  $_FILES['file']['type'] = strtolower($_FILES['file']['type']);
  
  if ($_FILES['file']['type'] == 'image/png' || $_FILES['file']['type'] == 'image/jpg' || $_FILES['file']['type'] == 'image/gif' || $_FILES['file']['type'] == 'image/jpeg' || $_FILES['file']['type'] == 'image/pjpeg')
  {
      // setting file's mysterious name
      $filename = md5(date('YmdHis')).'.jpg';
      $file = $dir.$filename;
  
      // copying
      copy($_FILES['file']['tmp_name'], $file);
  
      // displaying file    
      $array = array(
          'filelink' =&gt; '/images/'.$filename
      );
  
      echo stripslashes(json_encode($array));   
  
  }
  
  ?&gt;
  </code></pre>
  
  <p><strong>DATA JSON FILE</strong> - (imageGetJson: '../demo/json/data.json')</p>
  
  <pre><code>[
      { "thumb": "json/images/1_m.jpg", "image": "json/images/1.jpg", "title": "Image 1", "folder": "Folder 1" },
      { "thumb": "json/images/2_m.jpg", "image": "json/images/2.jpg", "title": "Image 2", "folder": "Folder 1" },
      { "thumb": "json/images/3_m.jpg", "image": "json/images/3.jpg", "title": "Image 3", "folder": "Folder 1" },
      { "thumb": "json/images/4_m.jpg", "image": "json/images/4.jpg", "title": "Image 4", "folder": "Folder 1" },
      { "thumb": "json/images/5_m.jpg", "image": "json/images/5.jpg", "title": "Image 5", "folder": "Folder 1" },
      { "thumb": "json/images/1_m.jpg", "image": "json/images/1.jpg", "title": "Image 6", "folder": "Folder 1" },
      { "thumb": "json/images/2_m.jpg", "image": "json/images/2.jpg", "title": "Image 7", "folder": "Folder 1" },
      { "thumb": "json/images/3_m.jpg", "image": "json/images/3.jpg", "title": "Image 8", "folder": "Folder 1" },
      { "thumb": "json/images/4_m.jpg", "image": "json/images/4.jpg", "title": "Image 9", "folder": "Folder 1" },
      { "thumb": "json/images/5_m.jpg", "image": "json/images/5.jpg", "title": "Image 10", "folder": "Folder 2" },
      { "thumb": "json/images/1_m.jpg", "image": "json/images/1.jpg", "title": "Image 11", "folder": "Folder 2" },
      { "thumb": "json/images/2_m.jpg", "image": "json/images/2.jpg", "title": "Image 12", "folder": "Folder 2" } 
  ]
  </code></pre>
  
  <p><strong>Extra Information:</strong></p>
  
  <p>At first I couldn't get the image library to display any images, again after browsing stackoverflow i found: (<a href="https://stackoverflow.com/questions/332988/get-iis6-to-serve-json-files-inc-post-get">Get IIS6 to serve JSON files (inc. POST,GET)?</a>) which said:</p>
  
  <p>By default, IIS in W2K3 and above won't serve files that aren't of a MIME type that it knows about (instead returning 404 errors).</p>
  
  <p>You need to add a MIME type to IIS to allow it to serve that type of file. You can set it at the site level or at the server level.</p>
  
  <p>To set this for the entire server:</p>
  
  <pre><code>Open the properties for the server in IIS Manager and click MIME Types
  Click "New". Enter "JSON" for the extension and "application/json" for the MIME type.
  </code></pre>
  
  <p>After doing this i was able to click on the 'insert image' button and see the actual images on the server with the option choose.</p>
  
  <p>Now i need to start re-writting the above above into Classic ASP.</p>
  
  <p>For the purpose of this question , I created a new page called: 'all_uploads_classic_asp.html' which is basicly a copy of 'all_uploads.html' with some amended code, please see my changes to the code below:</p>
  
  <p>original version:</p>
  
  <pre><code>    &lt;script type="text/javascript"&gt;
      $(document).ready(
          function()
          {
              $('#redactor_content').redactor({   
                  imageUpload: '../demo/scripts/image_upload.php',
                  fileUpload: '../demo/scripts/file_upload.php',
                  imageGetJson: '../demo/json/data.json'
              });
          }
      );
      &lt;/script&gt;   
  </code></pre>
  
  <p>amended version:</p>
  
  <pre><code>    &lt;script type="text/javascript"&gt;
      $(document).ready(
          function()
          {
              $('#redactor_content').redactor({   
                  imageUpload: '../demo/scripts/image_upload.asp',
                  fileUpload: '../demo/scripts/file_upload.asp',
                  imageGetJson: '../demo/json/data.json'
              });
          }
      );
      &lt;/script&gt;   
  </code></pre>
  
  <p>Then I created a new page called 'image_upload.asp', which is in the same directory as the original PHP version 'image_upload.php'</p>
  
  <p><strong>CLASSIC ASP UPLOAD SCRIPT</strong></p>
  
  <pre><code>&lt;%
  ' This is a simplified example, which doesn't cover security of uploaded images. 
  ' This example just demonstrate the logic behind the process in Classic ASP
  ' Written by I.Hekkenberg (DevCentral)
  
  ' files storage folder and path
  Dim MySaveFolder, MySaveFolderPath
      MySaveFolder     = "../demo/json/images/"
      MySaveFolderPath = "d:\internet\root\www\devcentral.co.uk\wwwroot\demo\wysiwyg\demo\json\images\"
  
  ' Server / Script Timeout for storage larger images
      Server.ScriptTimeout = 1200
      Set objUpload = Server.CreateObject("Persits.Upload")
          On Error Resume Next
          objUpload.OverwriteFiles = False
          objUpload.SetMaxSize 5242880    ' Limit files to 5MB
          objUpload.SaveVirtual(MySaveFolder)
  
          ' display error message
          If Err &lt;&gt; 0 Then 
              Response.Write "&lt;br /&gt;ERROR file uploading: " &amp; Err.Description &amp; " | " &amp; MySaveFolder
              Err.Clear
          ' no error occured so continue as normal
          Else
              ' ======================================================
              ' HELP NEEDED WITH REWRITTING THE BELOW INTO CLASSIC ASP
              '                                                       
              '   // displaying file                                  
              '   $array = array(                                     
              '   'filelink' =&gt; '/images/'.$filename                  
              '   );                                                  
              '   echo stripslashes(json_encode($array));             
              '                                                       
              ' ======================================================
          End If
      Set objUpload = Nothing
  %&gt;
  </code></pre>
  
  <p>Now i'm stuck where to go next, thanks</p>
  
  <p>If you need more info please ask and i will update asap</p>
  
  <p>Iwan Hekkenberg</p>
  
  <p><strong>UPDATE: 16/01/2013</strong></p>
  
  <p>I have followed the instructions of 'ulluoink' to amend the code to the following, however still no luck with actual uploading of the image.
      &lt;%
      ' This is a simplified example, which doesn't cover security of uploaded images. 
      ' This example just demonstrate the logic behind the process in Classic ASP
      ' Written by I.Hekkenberg (DevCentral)</p>
  
  <pre><code>' files storage folder and path
  Dim MySaveFolder, MySaveFolderPath
      MySaveFolder     = "../demo/json/images/"
      MySaveFolderPath = "D:\internet\root\www\devcentral.co.uk\wwwroot\demo\wysiwyg\demo\json\images\"
  
      ' Server / Script Timeout for storage larger images
      Server.ScriptTimeout = 1200
      Set objUpload = Server.CreateObject("Persits.Upload")
          objUpload.OverwriteFiles = False
          objUpload.SetMaxSize 5242880    ' Limit files to 5MB
          objUpload.SaveVirtual(MySaveFolder)
  
          ' ======================================================
          ' HELP NEEDED WITH REWRITTING THE BELOW INTO CLASSIC ASP
          '                                                       
          '   // displaying file                                  
          '   $array = array(                                     
          '   'filelink' =&gt; '/images/'.$filename                  
          '   );                                                  
          '   echo stripslashes(json_encode($array));             
          '                                                       
          ' ======================================================
          ' Amended code by 'ulluoink'
          ' write json back to client
          with response
            .codePage = 65001
            .charset = "utf-8"
            .contentType = "application/json"
          end with
  
          For Each File in objUpload.Files
              response.write "{ ""filelink"": """ &amp; MySaveFolder &amp; "/" &amp; File.FileName &amp; """ }"
          Next
          ' ======================================================
      Set objUpload = Nothing
  %&gt;
  </code></pre>
  
  <p>How could one debug this if nothing is happening or showing any signs of errors? I can't seem to find anything in the log files either. </p>
  
  <p>PS: the above code has been amended. I removed error handling for classic asp, no luck at all.</p>
  
  <p><strong>UPDATED: 16/01/2013</strong></p>
  
  <p>Ok, so there was a error with finding the image_upload.asp page, which was pretty lame ;(, after installing firebug and retifying the 404 error to the image_upload.asp, I found a new error within the firebug console:</p>
  
  <p>TypeError: rawString.match(...) is null
     [Break On This Error]    </p>
  
  <p>var jsonString = rawString.match(/{(.|\n)*}/)[0];</p>
  
  <p>Which refers to the redactor.js file: (<a href="http://demo.devcentral.co.uk/wysiwyg/redactor/redactor.js" rel="nofollow noreferrer">http://demo.devcentral.co.uk/wysiwyg/redactor/redactor.js</a>)</p>
  
  <pre><code>        uploadLoaded : function()
          {
              var i = $('#' + this.id)[0];
              var d;
  
              if (i.contentDocument)
              {
                  d = i.contentDocument;
              }
              else if (i.contentWindow)
              {
                  d = i.contentWindow.document;
              }
              else
              {
                  d = window.frames[this.id].document;
              }
  
              // Success
              if (this.uploadOptions.success)
              {
                  if (typeof d !== 'undefined')
                  {
                      // Remove bizarre &lt;pre&gt; tag wrappers around our json data:
                      var rawString = d.body.innerHTML;
                      var jsonString = rawString.match(/\{(.|\n)*\}/)[0];
                      var json = $.parseJSON(jsonString);
  
                      if (typeof json.error == 'undefined')
                      {
                          this.uploadOptions.success(json);
                      }
                      else
                      {
                          this.uploadOptions.error(this, json);
                          this.modalClose();
                      }
                  }
                  else
                  {
                      alert('Upload failed!');
                      this.modalClose();
                  }
              }
  
              this.element.attr('action', this.element_action);
              this.element.attr('target', '');
  
          },
  </code></pre>
  
  <p><strong>Update and final result: 18/01/2013</strong></p>
  
  <p>Once again with the help of 'ulluoink', who pointed out to me that the path in the upload script was providing me the headaches, it become clear that Firebug debugging tool is going to be my tool to use while debugging scripting like json, I was very impresed by the fact that this debugger was given the answer allong, thanks 'ulluoink' for helping me out with this problem.</p>
  
  <p>below I will post the final code I have used to let this work:</p>
  
  <p><strong>Final Redactor (WYSIWYG) - image_upload.asp</strong></p>
  
  <pre><code>&lt;%
  ' This is a simplified example, which doesn't cover security of uploaded images. 
  ' This example just demonstrate the logic behind the process in Classic ASP
  ' Written by I.Hekkenberg (DevCentral)
  
  ' files storage folder and path
  Dim MySaveFolder : MySaveFolder      = "../json/images"
      Server.ScriptTimeout = 1200
      Set objUpload = Server.CreateObject("Persits.Upload")
          objUpload.OverwriteFiles = False
          objUpload.SetMaxSize 5242880    ' Limit files to 5MB
          objUpload.SaveVirtual(MySaveFolder)
          ' code below provide by 'ulluoink'
          ' write json back to client
          with response
            .codePage = 65001
            .charset = "utf-8"
            .contentType = "application/json"
          end with
  
          For Each File in objUpload.Files
              response.write "{ ""filelink"": ""json/images/" &amp; File.FileName &amp; """ }"
          Next
          ' ======================================================
      Set objUpload = Nothing
  %&gt;
  </code></pre>