Access Headers when using fetch in javascript - javascript

I am sending a zip file from my nodejs server to the browser using the following
res.set("Content-Type", "application/octet-stream");
res.set("Content-disposition", `attachment; filename="`+zip_name+`.zip"`);
res.set("Content-Length", zipBuff.length);
res.send(zipBuff);
I am then fetching it by using :
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
return response.blob();
})
.then(response => {
const blob = new Blob([response], {type: 'application/zip'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "blah.zip";
document.body.appendChild(a);
a.click();
});
I would like to be able to use zip_name instead of blah for the filename but I can't figure out how to access the headers (in that case Content-disposition) of the response with fetch.
Could someone please explain how it's done ?

Return blob and headers in object
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
const headers = response.headers
return { blob: response.blob(), headers }
})
.then(({blob, headers}) => {
/// now you can access to **headers** and blob data
});
UPD:
To access the headers use headers.get("Header name").split('=').pop()
UPD1:
const foo = async () => {
const response = await fetch("/my/url", {
method: "POST",
body: formData,
})
if(!response.ok)
thorw new Error("Some error happend")
const blod_data = await response.blob()
const header_with_name = response.headers.get("Header name").split('=').pop()
// do something with it
}

In the first promise arrow function you have access to the HTTP response headers. If you update it to return the promise from the blob function call. Then in this nested function you can return an object that includes the header value to the outer second arrow function that processes the blob data.
Updated fetch example that includes processing the Promise returned from blob-function call.
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
return response.blob().then((data) => {
return {
data: data,
filename: response.headers.get('Content-disposition'),
};
});
})
.then(({ data, filename }) => {
const blob = new Blob([data], { type: 'application/zip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = filename.split('=')[1];
document.body.appendChild(a);
a.click();
});
Thank you Chapo for pointing out the issue with my previous example

Related

including image in request body as binary data

I need to include the image as binary data in my uploading request using multipart form data, and it seems not working, any advise will be appreciated.
my code:
const [selectedFile, setSelectedFile] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'application/octet-stream' }));
const data = {
uploadLink,
formData,
};
const headers = {
'Content-Type': 'application/octet-stream' ,
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
await axios
.post(`${backendPostPath}/thumbnail-upload`, data, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(response);
});
} catch (error) {
console.log(error);
}
};
const handleFileSelect = (event) => {
setSelectedFile(event.target.files[0]);
};
include formData as axios data parameter instead of your data object, so you can also include uploadLink in the formData:
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'application/octet-stream' }));
formData.append('uploadLink', uploadLink)
//...
await axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})

Download CSV files with HttpClient in ReactJS

I'm trying to make an API request using HttpClient to download a CSV file. I had to switch from Axios to HttpClient due to ForgeRock authentication that requires a bearer token. I'm having an issue where the response coming back does not have response.data. Where would I find the data to download to CSV?
My code:
fetchCSV = date => {
const url = "https://<URLdownloadLink>?runDate="+date;
const method = "GET";
HttpClient
.request({
url,
method,
bypassAuthentication: false,
responseType: 'blob',
init: {},
timeout: 5000
})
.then((response) => {
console.log("data", response)
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'Asset Manager.csv');
document.body.appendChild(link);
link.click();
link.remove();
})
.catch(error => {
console.log("error", error);
})
}
The response I'm getting back is the below. The response does not have "response.data" as an object key. When I open the CSV it only has "undefined".
This is my response.body:
You are using response.data instead of response.body?
Thats why it says undefined.
Remember CSV is just plain text and response.data is undefined.
fetchCSV = date => {
const url = "https://<URLdownloadLink>?runDate=" + date;
const method = "GET";
HttpClient
.request({
url,
method,
bypassAuthentication: false,
responseType: 'blob',
init: {},
timeout: 5000
})
.then((response) => {
console.log("data", response)
const url = window.URL.createObjectURL(new Blob([response.body]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'Asset Manager.csv');
document.body.appendChild(link);
link.click();
link.remove();
})
.catch(error => {
console.log("error", error);
})
}

"blob".then is not a function when trying to generate pdf in react js

I am sending the below response from my REST Api .
{
"value": "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9TL0phdmFTY3JpcHQvSlModGhpcy56b29tID0gMTAwOyk+PgplbmRvYmoKNSAwIG9iago8PC9Db2xvclNwYWNlL0RldmljZUdyYXkvU3VidHlwZS9JbWFnZS9IZWlnaHQgMTUwL0ZpbHRlci9GbGF0ZURlY29kZS9UeXBlL1hPYmphkNkwEVng0L00DhlcQ6ysIV4GNaOajLDQGlbKEIuFcJchdvr0W/z0aY+lZJyy+pmGsnrODq3AQiAQCAQCiRDHKaRFx0iOEAGhh40g1P0IsjS9pXbPlEzDoYf1OKTkDjFdQ6ysIXaYzMRC17KaLtIpQxdTKUPs9Gm646LMQnT6NJeFXjazUIotCx3mrcWQabf6qG8iEAgEAoEmsW7jOIXU6BidLK2BkEZBFP88qhr9R42IKBwiqdSMSBnlGjL2GlLDZOZqMuuUIZsuQ5bp0/xSMkdl9YZdyfy1GOK2W4z6JgKBQCAQaBJLFyDTZwphpxCJjpHQGGYbPAn/JQ/DX/YVtf/Rq19v18QeBP+Sh+Gv+wra/+jVr7foAKKKKACiiigD5g/aO/wCSh6f/ANgqP/0bLXj9ewftHf8AJQ9P/wCwVH/6Nlrx+gAooooAK6DwJ/yUPw1/2FbX/wBGrXP10HgT/kofhr/sK2v/AKNWgD7fooooA8f/AGjv+Seaf/2FY/8A0VLXzBX0/wDtHf8AJPNP/wCwrH/6Klr5goAK+n/2cf8Aknmof9hWT/0VFXzBX0/+zj/yTzUP+wrJ/wCioqAPYKKKKACiiigAooooAKKKKACiiigD5g/aO/5KHp//AGCo/wD0bLXj9ewftHf8lD0//sFR/wDo2WvH6ACvt/wJ/wAk88Nf9gq1/wDRS18QV9v+BP8Aknnhr/sFWv8A6KWgDoK5/wAd/wDJPPEv/YKuv/RTV0Fc/wCO/wDknniX/sFXX/opqAPiCiiigAooooAKKKKACiiigAooooA6DwJ/yUPw1/2FbX/0atfb9fEHgT/kofhr/sK2v/o1a+36ACiiigAooooAKKKKACviDx3/AMlD8S/9hW6/9GtX2/XxB47/AOSh+Jf+wrdf+jWoA5+ug8Cf8lD8Nf8AYVtf/Rq1z9dB4E/5KH4a/wCwra/+jVoA+36KKKAPH/2jv+Seaf8A9hWP/wBFS18wV9P/ALR3/JPNP/7Csf8A6Klr5goAK+n/ANnH/knmof8AYVk/9FRV8wV9P/s4/wDJPNQ/7Csn/oqKgD2CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK4P4s+NdS8B+FbXVNLgtJp5b1LdlukZlClHbI2spzlB39a7yvH/wBo7/knmn/9hWP/ANFS0AcB/wANHeMP+gbof/fib/47R/w0d4w/6Buh/wDfib/47Xj9FAH0P4b8N2fx306TxR4okns761lOnpHpjCOMxqBICRIHO7Mrc5xgDj12P+GcfB//AEEtc/7/AMP/AMao/Zx/5J5qH/YVk/8ARUVewUAeP/8ADOPg/wD6CWuf9/4f/jVcRf8Axr8SeDtRufC+nWWlS2OjSvp9vJcRSNI0cJMalyJACxCjJAAz2FfS9fEHjv8A5KH4l/7Ct1/6NagD0D/ho7xh/wBA3Q/+/E3/AMdqnq3x98Vazo19pdxp+jLBe28lvI0cMoYK6lSRmQjOD6GvK6KACiiigD2D9nH/AJKHqH/YKk/9GxV9P18wfs4/8lD1D/sFSf8Ao2KvKACiiigAooooAKKKKACvmD9o7/8L0luZm8gMjQgMCBSL0lEIFs8YzkyMWI2MGVkYzdkYTVlZWQyMzYyNTliYWRiYTVjMGY+PDMzYWYzZTBkOGM1MjFhNzVlMjk2MGQwZDIzZjJkY2U2Pl0vUm9vdCAyMyAwIFIvU2l6ZSAyNT4+CnN0YXJ0eHJlZgoxODA2OTIKJSVFT0YK",
"transid": "transid"
}
I am trying to convert the value which is byte data to pdf using React js.
Below is my implementation:
handleSubmit = e => {
e.preventDefault();
let url = "http://localhost:8080/getPDF"
fetch(url, {
method: "POST",
body: JSON.stringify(this.state.transId),
})
responseType: 'blob'
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.value],
{type: 'application/pdf'});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
};
But I am getting the following error.Can anyone please suggest where I am going wrong?
Uncaught TypeError: "blob".then is not a function
You cannot do .then() after a string (must follow a promise). You probably meant this line responseType: 'blob' to be one line higher up, inside the object?
handleSubmit = e => {
e.preventDefault();
let url = "http://localhost:8080/getPDF"
fetch(url, {
method: "POST",
body: JSON.stringify(this.state.transId),
responseType: 'blob' // <-- MOVE THIS LINE INTO REQUEST
})
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.value],
{type: 'application/pdf'});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
};

Is it possible to send data and files in the same request?

I have an API that receives uploads of APP files and images
To send from APP to the API I use fetch
const data = new FormData();
let i = 0;
export const dataPush = (fileUri, fileType, fileName) => {
data.append('file'+i, {
uri: fileUri,
type: fileType,
name: fileName
});
i++;
};
export const uploadFiles = () => {
console.log(data);
fetch('http://192.168.0.23/apiapp/public/api/annex', {
method: 'post',
body: data
}).then(res => {
console.log(res)
});
}
But I'd like to send in the same request data obtained from a form
But I did not find a way to do it, always or just send the data, or just send the files
Is it possible to send everything in the same request? And if possible, how?
You just append whatever data that you desire that isn't file data to the FormData object.
data.append("not_a_file", "This is a string");
I did so based on Quentin's response and it worked
const formData = new FormData();
const i = 0;
export const filePush = (fileUri, fileType, fileName) => {
formData.append('file'+i, {
uri: fileUri,
type: fileType,
name: fileName
});
i++;
};
export const dataPush = (name, content) => {
formData.append(name, content);
};
export const uploadFiles = () => {
fetch('http://192.168.0.23/apiapp/public/api/annex', {
method: 'post',
body: formData
}).then(res => {
console.log(res._bodyText)
}).catch(error => {
console.log(error.message)
});
}

Creating PDF from request response doesn't work with axios but works in native xhr

In order to force download PDF from server I tried to use axios and native xhr object. The reason is that I have to send post request, because I pass too much data to server, so the option with simple link (like site.ru/download-pdf won't work for me).
Even though I finally managed to do this with Xhr, I still don't have a clue why axios way doesn't work.
Here is how I do this with xhr and it works for me:
let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status === 200) {
let blob = new Blob([this.response], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
}
};
xhr.send("data=" + data);
Here is "axios-way" and I actually get PDF with correct number of pages, but they are all empty:
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'arraybuffer'
}).then((response) => {
let blob = new Blob([response.data], { type:"application/pdf" })
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
})
Axios is already configured to send Authorization token.
I put Application/x-www-form-urlencoded in xhr because otherwise I couldn't get data in server side.
Even though xhr works, I'd prefer to use axios since I use it everywhere and I'm just curios what I'm doing wrong. I tried different solutions, and only native xhr did the job.
The following works for me:
axios.post("http://localhost:8080/reports/my-report/",
data,
{
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
Let me know if this helps.
Cheers!
For whatever reason the pdf is downloading but any content passed is not appearing resulting in a blank pdf.
I found this code snippet that is similar but results in a pdf with content.
axios({
url: '/pdf',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
there was some feedback stating that it didnt work on IE 11, I have not tested it but a solution was posted using FileSaver.js
axios({
url: '/pdf',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
FileSaver.saveAs(new Blob([response.data]));
});
There is a special responseType: 'blob':
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'blob'
}).then((response) => {
let link = window.URL.createObjectURL(blob)
link.download = 'Results.pdf'
link.click()
})
Or you can use window.open method:
axios.post(`order-results/${id}/export-pdf`, {
data,
responseType: 'blob'
}).then((response) => {
window.open(URL.createObjectURL(response.data));
})
You're getting empty PDF 'cause no data is passed to the server. You can try passing data using data object like this
axios.post(`order-results/${id}/export-pdf`, {
data: {
firstName: 'Fred'
},
responseType: 'arraybuffer'
}).then((response) => {
console.log(response)
let blob = new Blob([response.data], { type: 'application/pdf' } ),
url = window.URL.createObjectURL(blob)
window.open(url); // Mostly the same, I was just experimenting with different approaches, tried link.click, iframe and other solutions
});
By the way I gotta thank you so much for showing me the hint in order to download pdf from response. Thank ya :)
var dates = {
fromDate: 20/5/2017,
toDate: 25/5/2017
}
The way in which I have used is,
axios({
method:'post',
url:'/reports/interval-dates',
responseType:'arraybuffer',
data: dates
})
.then(function(response) {
let blob = new Blob([response.data], { type: 'application/pdf' } );
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'Report.pdf';
link.click();
});

Categories

Resources