My web page has a link
href="https://...myapi.../files/get-user-role-file?fileID=etc..." target="_blank"
The web api call (get-user-role-file) returns a file with a mime type and a content disposition of inline.
the code returns a HttpResponseMessage. here is some of the code
ByteArrayContent content = new ByteArrayContent(_bytes);
string dispositionType = "inline";
if (_mimetype.IndexOf("octet-stream") > 0) dispositionType = "attachment";
ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue(dispositionType) {
FileName = _filename
};
MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(_mimetype);
response.Content = content;
response.Content.Headers.ContentDisposition = contentDisposition;
response.Content.Headers.ContentLength = _bytes.Length;
response.Content.Headers.ContentType = contentType;
This works in chrome and safari and firefox. In Edge it works for me in VS debug or in InPrivate mode or when run locally from my machine in IIS. It also works if the file type is one that can be opened in the browser OR if I have Fiddler running. BUT it does not work, for example, with a Excel doc in Edge run normally off of the web server. It does work for everyone else I have asked so far.
I have tried updating Edge and clearing all history.
What happens is a new tab is opened with the file URL and the downloads modal opens with a file named get-user-role-file.json and a message says "Couldn't download - Something went wrong...". In the network tab of the dev tools the call returns OK 200 and no error but also no response (Failed to load response data: No resource with given identifier found).
It's a mystery.
Related
I am able to successfully attach PDF file with ServiceNow table record using GlideSysAttachment API and attachment.write() function in script, however whenever I download and try to open same, I get the error shown in below screenshot.
Code snippet
(function execute() {
try{
var rec = new GlideRecord('incident');
var attachment = new GlideSysAttachment();
var incidentSysID = incident.number;
rec.get(incidentSysID);
var fileName = 'Test_Incident.pdf';
var contentType = 'application/pdf'; // Also tried with contentType as 'text/pdf'
var content = pdf_content;
var agr = attachment.write(rec, fileName, contentType, content);<br>
gs.info('The PDF attachment sys_id is: ' + agr);
}catch(err){
gs.log('Got Error: ' + err);
gs.info(err);
}
})()
I also tried "AttachmentCreator" with ecc_queue within script but same error occurs. Below is code for it.
(function execute()
{var attCreator = new GlideRecord('ecc_queue');
attCreator.agent = "AttachmentCreator";
attCreator.topic = "AttachmentCreator";
attCreator.name = "Test.pdf" + ":" + "text/pdf";
//Also tried, "Test.pdf:application/pdf"
attCreator.source = "incident"+":"+ incident.number;
// Record Table name and sys_id of the particular record
var content = pdf_content; // pdf_content is any string variable
var stringUtil = new GlideStringUtil();
var base64String = stringUtil.base64Encode(content);
var isValid=GlideStringUtil.isBase64(base64String);
var base64String= gs.base64Encode(content);
gs.info("Is valid base64 format in ecc_queue ? "+ isValid);
attCreator.payload = base64String; //base64 content of the file
attCreator.insert();
})()
I am able to attach and view excel and word files with similar scripts without any issues. I have checked system properties for attachments but everything looks fine. I am able to view the PDF file uploaded from UI to particular table records however not the one I attach via REST API or scripts.
I have also tried sending encoded data as bytes, base64 or simple string but nothing seems to work. I don't get any errors and attachment id is returned each time on creation of attachment.
After modifying my code slightly for above functions w.r.t scoped application instead of global; I got some information from logs when I debug:
05:38:38.411 Security restricted: File type is not allowed or does not match the content for file Test.pdf
05:38:38.410 Security restricted: MIME type mismatch for file: Test.pdf. Expected type:application/pdf, Actual type: text/plain
05:38:38.394 App:XYZ App x_272539_xyz_ap: Is valid base64 format in ecc_queue ? true
First a comment: This line in your code is accidentally working -- make sure you understand that a task number is not the object sys_id
var incidentSysID = incident.number; // should be incident.sys_id
Next, it's unclear where the PDF content is coming from. IF your complete code is listed, I would expect the errors given as you have noted that pdf_content is "any string variable."
ServiceNow does have a the capability to create a PDF from an HTML argument.
Generating a PDF from HTML
Here's a helpful blog post for getting a PDF (Platform generated) of an existing record:
Love PDF? PDF loves you too
I wrote a program on UWP that stores text in a .txt file which is then voiced to the client. This worked really well when using an HTTP URI but now that site uses HTTPS the program crashes with the error:
System.Net.Http.HttpRequestException: 'Response status code does not indicate success: 401 ().'
The line that it crashes on is:
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If I change the link to HTTP the program works fine again. Does anyone know how I can fix this please? Or is it just not possible?
var uriBing = new Uri(#"https://mydomain/net/hal2001/Actions/HALSpeak/speak.txt");
//set storageFolder as the location of the local app storage folder.
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
//Create a local file to be used to write the URL file to.
StorageFile sampleFile2 = await storageFolder.CreateFileAsync("status2.txt", CreationCollisionOption.ReplaceExisting);
//Write to local file the value stored in the URL file so they match.
var cli = new HttpClient();
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If Have tried the following but still not happy.
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("username", "pass");
HttpClient cli = new HttpClient(handler);
I checked the IIS server application > SSL Settings and SSL Settings is set to 'Require SSL' with client certificates set to Accept.
After a long time lurking, its time to ask my first question...
I'm having trouble with an AJAX query that used to work prior to moving to AWS.
Previously, My web site was hosted on a WAMP server for testing and development and the following relevant code worked fine.
//Read XML file from disc and send file content to other functions\\
function Get_XML_File(){
var XML_File_Path = File_Path + Client_Code + '/' + ID + '/' + ID + '_Analysed_Wave.web'
var xhttps = new XMLHttpRequest();
xhttps.onreadystatechange = function() {
if (xhttps.readyState == 4 && xhttps.status == 200){
Read_Meta_Data(xhttps)
Read_Time_Status(xhttps)
Read_Wave_Height(xhttps)
;}
};
xhttps.open("GET", XML_File_Path, true);
xhttps.send();
}
//Extract Header Data from XML file\\
function Read_Meta_Data(xml) {
var xmlDoc = xml.responseXML;
// Client//
var Client_ID = xmlDoc.getElementsByTagName('Client_ID')[0].childNodes[0]
var Client_Name = xmlDoc.getElementsByTagName('Client_Name')[0].childNodes[0]
Recently, This site was moved to a Elastic Beanstalk distribution with AWS.
'www.atmocean.com.au' has been provisioned with an SSL certificate using the AWS certificate manager.
'assets.atmocean.com.au' is also covered by an SSL certificate and is mapped to a cloudfront distribution of a S3 bucket.
Within the S3 bucket are xml formatted files with a .web suffix (these are generated by proprietary software.)
When the relevent web page is viewed, the chrome console shows the following error: "Uncaught TypeError: Cannot read property 'getElementsByTagName' of null"
this error is in reference to this line:
var Client_ID = xmlDoc.getElementsByTagName('Client_ID')[0].childNodes[0]
What I can't understand is that when the 'Network' tab of the developer console is viewed, the resource is shown as correctly loaded with a status code of 200.
Further, the file content can be viewed in the 'response' tab.
Does this mean that the file has been correctly downloaded from the server to the client?
If so, why does code that formerly worked without error now fail to get the file content?
Does something other than a standard website configuration need to be provisioned through elastic beanstalk (or other means)?
Thanks in anticipation.
You receive a HTTP 200 meaning the server understand the request and can full-fill the request but then it delivers the content, when you execute Read_Meta_Data it does not mean the full content has been delivered
you could add a console.log(xml) and console.log(xmlDoc) to see the current content of your progress
what I would suggest you leverage your code to add a listener on the completion of the transfer
var xhttps = new XMLHttpRequest();
xhttps.overrideMimeType('text/xml');
xhttps.addEventListener("load", transferComplete, false);
function transferComplete(evt) {
// from here your transfer has been completed
}
note: there's also a loadend method which runs when the load has been completed (wether it has been successful or not - never used it)
Frederic,
Thanks for your response.
The clue was in the following line:
xhttp.overrideMimeType('text/xml');
because the xml files use a custom file extension it was being returned as a text string.
I've changed the function to now read as follows:
//Read XML file from disc and send file content to other functions\\
function Get_XML_File(){
var XML_File_Path = File_Path + Client_Code + '/' + ID + '/' + ID + '_Analysed_Wave.web'
var xhttp = new XMLHttpRequest();
xhttp.overrideMimeType('text/xml');
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200){
Read_Meta_Data(xhttp)
Read_Time_Status(xhttp)
Read_Wave_Height(xhttp)
;}
};
xhttp.open("GET", XML_File_Path, true);
xhttp.send();
}
xhttp.overrideMimeType('text/xml');
And with that one change, all is well with the world. (well my function at least.)
My situation is as follows:
I am reading and returning a PDF file from the server, which is then displayed within an iframe. The following code works fine with IE. However, when I access the site via Chrome, I get all junk characters.
while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0)
{
if (HttpContext.Response.IsClientConnected)
{
HttpContext.Response.BufferOutput = true;
HttpContext.Response.ContentType = "application/pdf";
HttpContext.Response.OutputStream.Write(buffer, 0, buffer.Length);
//HttpContext.Response.Flush();
}
}
When I flush the response, I do get to see the PDF correctly. The problem is that calling flush is resulting in "Server cannot set status after HTTP headers have been sent" warning on the server.
Question is: Why is flush needed for Chrome and if there is a way to avoid flush? So far, I have read all the posts and unable to resolve the server error associated with flushing.
Server - IIS7, Windows Server 2008 R2
App - ASP.Net 4.0.30319.0, C#, Ajax
I hope this will help you, change your controller to return FileResult
public FileResult DownloadPDF()
{
buffer = <bytes from your PDF file>;
return File(buffer, "application/pdf", "download.pdf");
}
Show PDF
public FileResult ShowPDF()
{
buffer = <bytes from your PDF file>;
return File(buffer, "application/pdf");
}
I've got an MVC 3 app that allows users to upload files with some data entry stuff. I've set up a controller that fetches those documents and buffers them out to the user like so
[OutputCache(Duration = 1200, VaryByParam = "id")]
public ContentResult GetNarrative(int id)
{
Response.Clear();
Response.BufferOutput = true;
Response.ContentType = "application/octet-stream";
var narrative = attachRepo.GetNarrative(id);
if (narrative == null || narrative.Narrative == null)
return null;
Response.AddHeader("Content-Disposition",
string.Format("attachment;filename={0}",
Server.UrlEncode(narrative.Filename)));
Response.OutputStream.Write(narrative.Narrative.ToArray(),
0, narrative.Narrative.ToArray().Length);
Response.OutputStream.Flush();
return Content("");
}
This works fine and well, the interesting thing is that when I have the output cache line, my firefox download dialog looks like this
However when I comment out the output cache line it looks like the expected dialog
This isn't really a blocking issue, as it works just fine in IE and Chrome just downloads by default, but I am curious why this would be happening and if anyone has experienced this and worked around it.
Thanks!
I've found that firefox ignores the filename in the Attachment. It tends to use he URL to set the filename.
Try putting at the end of the URL ?filename.docx
And see if it fixes things.