Download file from server with Flask and JS - javascript

I am trying to download a file when a user clicks on a particular button. This file is an image which gets created when the said button is pressed. What I want is, it should automatically download the image on the client's device.
I am using Flask on the server code, and ideally, the send_file function of Flask should trigger this auto download as it adds the Content-Disposition header.
On the client side, I have a JS code which uses fetch API to send a POST request to the server with some data, which is used for generating the image which is to be downloaded.
This is the JS code:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
res.json(); //Gives an error: Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
}).catch(err=>console.log(err));
}
And this is the Python code on the server:
#app.route('/image',methods=['POST'])
def generate_image():
cont = request.get_json()
t=cont['text']
print(cont['text'])
name = pic.create_image(t)
time.sleep(2)
return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")
But nothing is happening. The image doesnt get downloaded. However,the image is getting created on the server and is not corrupt
How do I resolve this? And is there some other way to do what I am trying to do?

You can do the below
return send_from_directory(dir, file_name, as_attachment=True)
This will download the file on the user's machine.
Edit:
BTW, if you create an html form like below, you do not need javascript.
<form action='action here' method='post'>
<input type='submit'>
</form>

As #clockwatcher mentioned a different question, I used the download.js module to handle the download of the image.
So my JS code looks like this now:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
return res.blob();
}).then(blob=>{
download(blob)
}).catch(err=>console.log(err));
}
And an addition to the script tag in the html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>
With no change in the Python server code.
It works now

Related

How to upload file in NodeJs to PocketBase

I'm working on a project where I need to upload many PDF files to a PocketBase collection.
I have all the files on my computer and I'd like to upload them using nodejs and the PocketBase JavaScript SDK. PocketBase expects me to send the file as a [file object], which is not possible in nodejs.
Ideally the code would look something like that:
const fileObject = loadFile(pathToFile);
const entry = {
nameField: "some-field",
fileField: fileObject
}
await pb.collection("my-collection").create(entry)
I didn't find any bits of code that could help creating a loadFile function.
You are supposed to send your form as multipart/form-data when uploading files to pocketbase.
Try:
const res = fetch(
"http://127.0.0.1:8090/api/collections/my-collection/records",
{
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: myFormWhichHasFiles,
}
)
Also, make sure you don't use JSON.stringify on your form when using multipart/form data.
Pro tip: if you leave out 'Content-type', it should default to multipart/form-data.

Display QRCode in HTML (google authenticator)

I made a POST request to get a QRCode
Here is the data I get from the response. The preview of the response works fine only I don't know how to use this data to display it in a tag on my html page for example. Any ideas?
It finally works as : (in async function)
const response = await fetch(URL_FOR_QRCODE, //your own url
{
method: "POST", //because my endpoint is a post method
credentials: 'include' //because I use cookies (its a auth qr code)
});
this.QRCodeSRC = URL.createObjectURL(await response.blob());

Sending image from flask to javascript

I am trying to send an image from the flask server to the web script. The first server connects to another API and gets an image. I don't want to save this image just forward it to the web application script.
#app.route('/api/image', methods=['GET'])
def return_image():
r = requests.get(f"{api_url}/image")
return send_file(
BytesIO(r.content),
mimetype='image/jpeg',
as_attachment=True,
attachment_filename='test.jpg')
I am trying to get this image by ajax request and display it.
function updateImage() {
$.ajax({
url: "/api/image",
type: "GET",
dataType: 'image/jpg',
success: function (res) {
$(theImg).attr("src", 'data:image/png;base64,'+ res);
M.toast({
html: 'Loading image: Success'
})
},
error: function () {
M.toast({
html: 'Loading image: Fail'
})
}
});
}
I tried to make this work but wasn't able to. I really appreciate your help.
At a glance your JS writes a data-uri to the src attribute, but res is actually the binary data with a image/png mimetype.
So you either need to base64 encode r.content on the server side, here's an example which actually creates the entire uri server side, then return that string and have your JS add that to the src attribute.
Or if you just want make your JS support the exisitng endpoint you could probably create a blob based on /api/image response, then write that to the img tag.

Save File through JQuery AJAX Call

I am using JQuery to send an AJAX request to a Node server (using Hapi). The server responds with a PDF file correctly, but I am trying to save the file locally. The catch is that the PDF should only return if the POST sent the right data. It's "protected" in other words and I don't want to just expose it publicly.
Frontend code:
$.get('http://localhost:3000').done(function (data) {
console.log(data);
});
Backend code:
server.route({
method: 'GET',
path: '/',
handler: async (request, h) => {
return h.file('./static/sample.pdf', {
mode: 'attachment',
filename: 'sample.pdf'
})
}
});
I receive the data but nothing happens in the front-end UI. How can I download the PDF that is sent automatically?
You can achieve that with html5 using
Download it!
Notice that this works only for same-origin URLs, or the blob: and data: schemes. And this gets overridden by the Content-Disposition header from the server.
If you want to do this programatically you could do this
const element = document.createElement("a")
element.setAttribute(
"href",
// you could also use base64 encoding here like data:application/pdf;base64,
"data:text/plain;charset=utf-8," + encodeURIComponent('pdf binary content here')
)
element.setAttribute("download", "file.pdf")
element.style.display = "none"
document.body.appendChild(element)
element.click()
document.body.removeChild(element)
Anyway this is only a useful method if u want to create/modify the downloaded data from the client side, but if u are getting it as it is from the server side then its better just to open a new url, letting the browser handle it.

Reactjs Nodejs file upload ftp via axios

I am trying to upload file using React Dropzone on ftp with Reactjs + AXIOS at front end, Nodejs + connect-multiparty at back end.
The problem is when I am sending file via front end using AXIOS, I am not getting the file at server in request.
My code to upload file using react-axios is
let data = new FormData()
data.append('file', file)
var setting = {
method: 'post',
url: 'my-server-url',
data:data,
headers: {
'Content-Type': 'multipart/form-data'
},
}
var response = axios(setting).then(response => { return response.data })
.catch(response => response = {
success: 500,
message: "Your submission could not be completed. Please Try Again!",
data: ""
});
while using postman, everything works fine. Server side api is working. only problem with client side request code.
Any help!!!
This is a very rookie mistake you're making probably because of the fact that you don't understand the way multipart works. For your client-side code to work, i.e form-data to be sent back to the backend, you need to:
Either remove the header and let the browser choose the header for you based on your data type
Or when using 'Content-Type': 'multipart/form-data', add a boundary to it
Multipart boundary looks like this,
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryABCDEFGHIJKLMNOPQRSTUVWXYZ'
Simply doing the following will solve the issue for you as the browser will take care of the headers needed.
axios.post('your-server-url', data).then(....)

Categories

Resources