I cannot file a way to upload a file in REDCAP using MATLAB web services. While this is possible using curl (see below), REDCAP API
is a REST API and the documentation for "Import file" says it it should support a POST request, I am
unable to find how to use MATLAB webwrite for this purpose.
Here is a code snippet:
url = 'xxxxx'; % REDCap API
token = 'xxxxxx'; % REDCap token
filename = 'xxxxx'; % filename
record = '1';
field = 'file';
% read file content
fid = fopen(filename, 'rb');
if fid==-1
error(['Cannot open ' filename])
end
data = char(fread(fid));
fclose(fid);
ops = weboptions('CertificateFilename', '', 'Debug', false);
result = webwrite(url, 'token', token, ...
'content','file', ...
'action', 'import', ...
'record', record,...
'field', field, ...
'file', data, ...
'returnFormat','csv', ops);
For the file parameter, REDCap API documentations says it corresponds to the "content of the file",
without saying how it must be formatted. I have also tried to use the filename instead of the file content because I have found that other implementations based on curl use the filename as parameter
(see below) but it did not work.
The response I get from REDCAP when using the above code is
The server returned the status 403 with message
"Forbidden" in response to the request to URL
http://172.17.210.219/redcap/redcap/api/.
which suggests that it might be a lack of privilege but I don't have problems uploading a file using a difference interface.
The following examples work but they rely on curl internally or externally:
url <- "http://172.17.210.219/redcap/redcap/api/"
file <- 'contents.m'
formData <- list("token"=token,
action='import',
content='file',
record='1',
field='file',
event='',
returnFormat='json',
file=httr::upload_file(file)
)
response <- httr::POST(url, body = formData, encode = "multipart")
result <- httr::content(response)
httr::POST relies on curl package, which is an interface to libcurl C library.
Similarly, a function in Matlab REDCap API interface also uses 'curl' which must be installed on the machine:
dToken = [ ...
'-F "token=', redcap_token, '"', ...
' -F "content=file"', ...
' -F "action=import"', ...
' -F "record=', record_num, '"', ...
' -F "event=', varargin{3}, '"', ...
' -F "field=', varargin{4}, '"', ...
' -F "filename=', [this_name, this_ext], '"', ...
' -F "file=@', temp, '"'];
unixCmd = ['curl ', hCmd2, ' -X POST ', hCmd2, ' ', dToken, ' ', redcap_url];
[uState, uResultUpload] = system( unixCmd ); % for PC
In both cases, curl takes the filename as argument and not the file content. Also, curl seems to be able to be able to send the filename
in addition to the file content to REDCap.