Passing file attachment to REST API

18 views
Skip to first unread message

Mark Orciuch

unread,
Apr 29, 2022, 8:13:56 PMApr 29
to dotCMS User Group
Hello,

I have an existing website feedback script which accepts user input and then passes it to REST API to create a contentlet and then send notification email to webmaster. I need to modify this to add file attachment capability.

In my script, I am building my post data like shown below but the contentlet gets created without the attachment:

var dataObj={        
        'contentType':'WebsiteFeedback'
      };
     
      dataObj.subject = $('#subject').val();
      dataObj.body = $('#body').val();
      dataObj.email = $('#email').val();
....................
      var fileObject = $('input[type=file]')[0].files[0];
      dataObj.attachment = fileObject; <----- this does not work
      dataObj.attachment = JSON.stringify(fileObject); <---- this does not work
...................
$.ajax({
                ##url: '/api/v1/workflow/actions/9ff4d190a6/fire',
                url: '/api/v1/workflow/actions/default/fire/NEW',
                type: 'PUT',
                cache: false,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: '{"contentlet":' + JSON.stringify(dataObj) + '}',        
                beforeSend: function(request) {
                  request.setRequestHeader('Authorization', 'Bearer *************');
                }

Any help making this work would be much appreciated.


jonathan...@dotcms.com

unread,
May 12, 2022, 8:15:35 AMMay 12
to dotCMS User Group
Hi Mark, I am not sure about how to do this on the library that you are using, but the request should looks 

--header 'Content-Type: application/json' \
--header 'Authorization: Basic YWRtaW5AZG90Y21zLmNvbTphZG1pbg==' \
--form 'json="{ \"contentlet\" : {
\"contentType\" : \"FileAsset\",
\"hostFolder\":\"default\",
\"fileName\":\"james.jpeg\",
\"title\":\"james.jpeg\"
}
}"' \
--form 'file=@"resources/WorkflowResource/testImages/james.jpeg"'

Basically you need to send a form-data/multipart request, in the example I am adding a file asset.

Thanks,
J

Mark Orciuch

unread,
May 13, 2022, 9:53:43 AMMay 13
to dotCMS User Group
I was able to make this work with the following JS code:

var fileObject;
if($('input[type=file]')[0] != undefined) {
fileObject = $('input[type=file]')[0].files[0];
}
if(fileObject) {
if(dataObj.subDepartments == undefined) dataObj.subDepartments = "{}";
if(dataObj.subDepartmentsList == undefined) dataObj.subDepartmentsList = "{}";
var dataObj2 = new FormData();
dataObj2.append("json", "{ \"contentlet\" : { \
\"contentType\": \"WebsiteFeedback\", \
\"department\": " + "\"" + dataObj.department + "\", \
\"employee\": " + "\"" + dataObj.employee + "\", \
\"siteFolder\": " + "\"" + dataObj.siteFolder + "\", \
\"targetTitle\": " + "\"" + dataObj.targetTitle + "\", \
\"targetEmail\": " + "\"" + dataObj.targetEmail + "\", \
\"email\": " + "\"" + dataObj.email + "\", \
\"phone\": " + "\"" + dataObj.phone + "\", \
\"subject\": " + "\"" + dataObj.subject + "\", \
\"message\": " + "\"" + dataObj.message + "\", \
\"fromName\": " + "\"" + dataObj.fromName + "\", \
\"subDepartments\": " + "\"" + dataObj.subDepartments + "\", \
\"subDepartmentsList\": " + "\"" + dataObj.subDepartmentsList + "\" \
} }");

$.ajax({
url: '/api/v1/workflow/actions/default/fire/NEW',
type: 'PUT',
enctype: 'multipart/form-data',
cache: false,
timeout: 600000,
processData: false,
contentType: false,
dataType: 'json',
data: dataObj2,
beforeSend: function(request) {
request.setRequestHeader('Authorization', 'Bearer *****');
},
success: function(data, status, xhr) {
#if($UtilMethods.isSet($deptId))
#set($dept = $dotcontent.find($deptId))
alert("$!dept.completionMessage");
window.location="/departments/${dept.legacyGroupName}";
#else
alert("Thank you for your feedback. Someone will get back to you as soon as possible.");
window.location="/";
#end
},
error: function(data,status,xhr) {
$('requestBtn').attr('disabled', false);
$('requestBtn').prop('disabled', false);
$( "button" ).removeClass( "disabled" ).addClass( "btn-primary" );
var errors = JSON.parse(data.responseText).errors;
var errorList = "\n\n";
if(errors) {
for(var i = 0; i < errors.length; i++)
{
errorList = errorList + errors[i].message + "\n";
}
}
alert("Uh Oh, your request failed. Please check your entries and try again: " + errorList);
},
});

Note that this will only work if the user selects a file. If no file is selected, the data has to be build differently and ajax call needs to be changed to something like this:

$.ajax({
url: '/api/v1/workflow/actions/default/fire/NEW',
type: 'PUT',
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: '{"contentlet":' + JSON.stringify(dataObj) + '}',
beforeSend: function(request) {
request.setRequestHeader('Authorization', 'Bearer *****');
},
success: function(data, status, xhr) {
#if($UtilMethods.isSet($deptId))
#set($dept = $dotcontent.find($deptId))
alert("$!dept.completionMessage");
window.location="/departments/${dept.legacyGroupName}";
#else
alert("Thank you for your feedback. Someone will get back to you as soon as possible.");
window.location="/";
#end
},
error: function(data,status,xhr) {
$('requestBtn').attr('disabled', false);
$('requestBtn').prop('disabled', false);
$( 'button' ).removeClass( 'disabled' ).addClass( 'btn-primary' );
var errors = JSON.parse(data.responseText).errors;
var errorList = "\n\n";
for(var i = 0; i < errors.length; i++)
{
errorList = errorList + errors[i].message + "\n";
}
alert("Uh Oh, your request failed. Please check your entries and try again: " + errorList);
},
});

Reply all
Reply to author
Forward
0 new messages