Sunday, June 2, 2024
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 15552  / 6 Years ago, fri, may 4, 2018, 12:00:00

Using javascript fetch and invoking a rest service that returns a blob if successful, otherwise returns an error message as json. How would this be handled in the fetch? The actual service is a asp.net web api implementation that returns a FileStreamResult (or FileContentResult) when successful, otherwise returns an error code with json containing the error message. Below is an example of what I'm trying to do:



fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
} else {
return response.json();
}

}).then(function(myBlob) { // here I would also like to function(jsonError)
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});

More From » asp.net-core

 Answers
19

Since you want to go down two fairly different paths, this is one of the relatively-rare situations where you probably want to nest handlers:



fetch('flowers.jpg').then(function(response) {
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});

[#54512] Monday, April 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;