'How to fetch FileStreamResult from API on React JS
I have dotnet core API return a FileStreamResult, but my React app does not get the response.data expected. I have tested the API on Postman and it brings the 200 with pdf OK. See my code:
API
[HttpPost]
[Route("downloadFile/{fileName}")]
public async Task<IActionResult> DownloadDoc(string fileName)
{
BlobServiceClient blobServiceClient = new BlobServiceClient(_storedconnectionString);
var container = blobServiceClient.GetBlobContainerClient(_azureContainerName);
var isExist = await container.ExistsAsync();
if (!isExist)
{
//Create new container
await container.CreateIfNotExistsAsync();
}
var blob = container.GetBlobClient(fileName);
if (await blob.ExistsAsync())
{
var a = await blob.DownloadAsync();
return File(a.Value.Content, a.ContentType, fileName);
}
return BadRequest();
}
REACT
export async function API_DownloadDoc(fileName){
const access_token = Cookies.get('access_token')
const requestOptions = {
method: "POST",
mode: 'cors',
headers: {
'Authorization': `Bearer ${access_token}`,
'Content-Type': 'application/json'
},
responseType: 'blob',
}
return await fetch(`${config.apiUrl}api/downloadFile/${fileName}`,
requestOptions).then(async (response) => {
const isJsonBlob = (data) => data instanceof Blob && data.type ===
"application/json"
const responseData = isJsonBlob(response?.data) ? await (response?.data)?.text() :
response?.data || {}
const responseJson = (typeof responseData === "string") ? JSON.parse(responseData) :
responseData;
return responseJson
})
.catch((error) => {
return error
})
}
Response I Get
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: https://localhost:55000/api/case/downloadDoc/file.pdf
[[Prototype]]: Response
I need the response on blob format. I would appreciate any feedback, thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
