In my Javascript client, I'm using Fetch API to call the server to retrieve a server-generated file. I'm using the following client-side code:
var _url = "";
var initParms = {
method: "GET",
mode: 'cors'
}
fetch(_url, initParms)
.then(response => {
if(response.ok){
alert(response.headers.get("content-disposition"));
return response.blob();
}
throw new Error("Network response was not OK.");
})
.then(blob => {
var url = new URL.createObjectURL(blob);
})
This actually works just fine. However, the server generates a filename
for the file and includes it in the response as part of the content-disposition
header.
I need to save this file to the user's machine using the filename
generated by the server. In Postman, I can actually see that the content-disposition
header of the response is set to: Content-Disposition: attachment;filename=myfilename.txt
.
I made an attempt to read the content-disposition
from the response (see the alert in my JS code), but I always get null
(even though the same response shows the content-disposition
in Postman).
Am I doing something wrong? Is there a way to retrieve the filename
using the fetch response? Is there a better way to get the filename
from the server along with the file?
P.S. This is my server-side code for returning the file:
Controller Action
public IHttpActionResult GetFile(){
return new FileResult("myfilename.txt","Hello World!");
}
FileResult Class
public class FileResult : IHttpActionResult
{
private string _fileText = "";
private string _fileName = "";
private string _contentType = "";
public FileResult(string name, string text)
{
_fileText = text;
_fileName = name;
_contentType = "text/plain";
}
public Task<HttpResponseMessage> ExecuteActionAsync(CancellationToken token)
{
Stream _stream = null;
if (_contentType == "text/plain")
{
var bytes = Encoding.Unicode.GetBytes(_fileText);
_stream = new MemoryStream(bytes);
}
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(_stream),
};
response.Content.Headers.ContentType =
new MediaTypeHeaderValue(_contentType);
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = _fileName
};
return response;
}, token);
Edit
My question was specifically about the fetch not the ajax api. Also, in my code, I showed that I was already reading the header from the response exactly like the accepted answer demonstrated on the suggested answer. However, as stated in my post, this solution was not working with fetch.