Programmatically Download an Attachment from a URL
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2024 11:57 AM - edited ‎08-09-2024 12:13 PM
Blog Post:
Have you ever wanted to download a file from a link and save it to a record? What about getting an inbound email with a download link to a csv which needs to be processed and transformed into records? Well, I had that requirement. I wasn't able to find anything specific to what I needed in the community so I wanted to share a snippet which accomplishes this. You can further expand on this to get it to work for different requirements like within an inbound email action.
Code Snippet:
//URL for download
var url = 'http://mywebsite.com/attachments/SomeFile.csv'; //csv file
//Use GlideHTTPRequest to download the file
var request = new GlideHTTPRequest(url);
var response = request.get();
var fileContent = response.getBody();
//Use the URL to name the file or set it to whatever you want
var fileName = url.substring(url.lastIndexOf('/') + 1);
//Initialize a record to save the attachment to like an incident or a data source record
var gr = new GlideRecord('incident');
gr.initialize();
gr.short_description = 'Downloaded File';
gr.insert();
//Save the attachment to created record using GlideSysAttachment
var attachment = new GlideSysAttachment();
attachment.write(gr, fileName, 'text/csv', fileContent);
Documentation:
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2024 12:02 PM
Hi @AJugovic ,
You can write an async/update BR and use the following script-
(function executeRule(current, previous /*null when async*/ ) { var endpointURL = current.u_url; var attachmentName = "Attachment Name" + current.number + ".mp4"; var request = new sn_ws.RESTMessageV2(); request.setHttpMethod('GET'); request.setEndpoint(endpointURL); request.saveResponseBodyAsAttachment('Table Name', current.sys_id, attachmentName); var response = request.execute(); if (response.getStatusCode() == 200) { // Get the response body (file content) var responseBody = response.getBody(); } else { gs.error("Failed to retrieve file. HTTP Status Code: " + response.getStatusCode()); } })(current, previous);
Please, don't forget to mark my answer as correct if it solves your issue or mark it as helpful if it is relevant for you!
Thanks & Regards,
Sumanth Meda
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2024 12:07 PM
Thank you, but this was more so meant as a blog post just to share with the community. That's definitely another option folks could use.