0

I have created a Cloud Page with a form to upload an image using this tutorial: https://sfmarketing.cloud/2020/02/29/create-a-cloudpages-form-with-an-image-file-upload-option/. I am able to successfully upload the image to Content Builder and also send a triggered email containing all of the form info using AMPScript, except I cannot for the life of me figure out how to grab the URL of the uploaded image in order to include it in the email. I see in the tutorial that the json response includes the image info as “fileProperties” but I don’t know how to retrieve that info.

"fileProperties":{
      "extension":"jpg",
      "fileSize":24328,
      "fileCreatedDate":"xxx",
      "width":700,
      "height":421,
      "publishedURL":"xxxx"
   },

Below is the file part of the form and the SSJS on page. The form processing page code is exactly as shown here: https://gist.github.com/zuzannamj/f87cdfaee61d850453cf10f1f180037a.

    <form class="grid-container text-left" id="campaignForm" action="https://pub.s1.exacttarget.com/xxxxxx" method="post"> 
         <div class="large-12 cell"> 
           <h4>File</h4> 
           <input id="file" type="file" accept="image/*" onchange="loadFile(event)"><br> 
           <img style="max-width: 50%" id="output"> 
        </div> 
        <div class="large-12 cell">     
           <button id="button" class="button large">Submit</button> 
        </div> 
    </form>

    <script runat="client">
           var loadFile = function(e) {
      document.getElementById("output").src = URL.createObjectURL(e.target.files[0])
    };

    function getBase64(e) {
      var n = new FileReader;
      n.readAsDataURL(e), n.onload = function() {
        var e = n.result.split(";base64,")[1],
          t = document.getElementById("file").files[0].name,
          i = t.split(".")[0],
          s = t.split(".")[1]

        fetch("https://pub.s1.exacttarget.com/xxxxxx", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            base64enc: e,
            fileName: i,
            assetName: s,

          })
        })
      }, n.onerror = function(e) {
        console.log("Error: ", e)
      }
    }
    document.getElementById("button").addEventListener("click", function() {
      var e = document.getElementById("file").files;
      e.length > 0 && getBase64(e[0])
    });
    </script>

Form processing code:

<script runat="server">
Platform.Load("Core","1.1.1");
try {
    //fetch posted data
    var jsonData = Platform.Request.GetPostData();
    var obj = Platform.Function.ParseJSON(jsonData);

    //prepare data for API call
    var base64enc = obj.base64enc;
    var fileName = obj.fileName;
    var assetName = obj.assetName;

    //match asset type with uploaded file 
    var assetTypes = { gif: 20, jpe: 21, jpeg: 22, jpg: 23, png: 28};

    var assetTypeID = assetTypes[assetName];

  //authenticate to get access token
  var authEndpoint = 'https://xxxxxx.auth.marketingcloudapis.com/' //add authentication endpoint
  var payload = {
    client_id: "xxxxxx", //pass Client ID
    client_secret: "xxxxxx", //pass Client Secret
    grant_type: "client_credentials"
  };
  var url = authEndpoint + '/v2/token'
  var contentType = 'application/json'

  var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
  if (accessTokenRequest.StatusCode == 200) {
    var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
    var accessToken = tokenResponse.access_token
    var rest_instance_url = tokenResponse.rest_instance_url
  }
  //make api call to create asset   
  if (base64enc != null) {
    var headerNames = ["Authorization"];
    var headerValues = ["Bearer " + accessToken];
    var jsonBody = {
      "name": fileName,
      "assetType": {
        "name": assetName,
        "id": assetTypeID
      },
      "file": base64enc,
      "category": { 
         "id": 7014 
      }
    };

    var requestUrl = rest_instance_url + "asset/v1/content/assets"

    var createAsset = HTTP.Post(requestUrl, contentType, Stringify(jsonBody), headerNames, headerValues);

  }

} catch (error) {
  Write("<br>error: " + Stringify(error));
}
</script>

Thanks in advance for any help you may be able to offer!

1 Answer 1

1

We're missing the server side code that does your triggered send etc, but with respect to the tutorial you mention, the last code snippet in the examples is where you get the URL of the uploaded asset...

var createAsset = HTTP.Post(requestUrl, contentType, Stringify(jsonBody), headerNames, headerValues);

The createAsset response returned by the API contains the created object along with it's published URL

var createAsset = HTTP.Post(requestUrl, contentType, Stringify(jsonBody), headerNames, headerValues);
var asset = Platform.Function.ParseJSON(createAsset);
var publishedUrl = asset.fileProperties.publishedURL;
5
  • Thanks, @Macca, I added my code to my question - it is exactly as you showed. I still don't understand how to access the URL. I tried: var asset = Platform.Function.ParseJSON(createAsset); var publishedUrl = asset.fileProperties.publishedURL; Variable.SetValue("@imgUrl",publishedUrl); and then %%=v(@imgUrl)=%% to print it out, as well as Write("Image URL:" + publishedUrl); but no luck. I need to grab the value so I can upsert it to a DE with the other form data.
    – Evangogh
    Mar 16, 2020 at 5:07
  • I've also tried var createAsset = HTTP.Post(requestUrl, contentType, Stringify(jsonBody), headerNames, headerValues); //stringify response var respo = createAsset.Response.toString(); //parse JSON var res = Platform.Function.ParseJSON(respo); //get the image url var imgURL = res.fileProperties.publishedURL; //initiate your data extension var myDE = DataExtension.Init(“xxxx-xxx-xxxx-xxxx-xxxx”); //add a new row with url to a data extensions var fileURL = myDE.Rows.Add({FileURL:imgURL}); Write(“File URL:” + fileURL); but still no luck.
    – Evangogh
    Mar 16, 2020 at 21:01
  • To debug, if you Write(createAsset) and Write(Stringify(asset)), what do you see?
    – Macca
    Mar 17, 2020 at 1:33
  • Write(createAsset) and Write(Stringify(asset)) both return "undefined".
    – Evangogh
    Mar 18, 2020 at 16:43
  • Ok, I'm an idiot - the DE I was attempting to write to had a primary key and of course, I was. not passing one through to it. All is good now! Thanks again for your help, @Macca.
    – Evangogh
    Mar 19, 2020 at 21:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .