0

I have a zip file in my server, and I want to create a download button for the user, heres my flask code:

@app.route("/profile", methods=["GET", "POST"])
def profile():

if request.method == "GET":

    return render_template("profile.html")

if request.method == "POST":

    #Some code

    return send_file(f"user_projects/delivery.zip")

And here's my JS code:

xhr.onreadystatechange = function () {
    
    if (this.readyState == 4 && this.status == 200) {     

        if (something) {
            some code
        }
        else {                        
            var zipFile = new Blob([this.response])               
            var url = URL.createObjectURL(zipFile)
     
            downloadLink.href = url;            
        }
    }
}

When I click the "a" element (downloadLink) I can download the zip file, but when I try to open it I get an error saying:

ERRORS: Is not archive WARNINGS: Headers Error

The zip file from the server is 100% fine, I can open it without any problem, the issue is when I download it from my website so I think there is something I am taking for granted. Any help is appreciated, thanks.

Alex
  • 139
  • 6
  • Have you tried specifying type: `new Blob([this.response], {'type':'application/zip'})`? – funnydman Nov 01 '21 at 05:43
  • Yes, but I get the same error. – Alex Nov 01 '21 at 05:50
  • How a browser opens information that is sent to a client is mostly browser-based. If you set the headers, try to set your browser to just download and not open. Alternatively try a different browser and check if that matters. – JustLudo Nov 01 '21 at 07:42
  • No luck, I am downloading the file and I get the same error, I am 99% sure that I am ignoring something in the javascript code, the request response says that I am sending a zip file with application/zip as the content type, I am not that good with javascript but seems ok to me. – Alex Nov 01 '21 at 07:54

1 Answers1

0

I got to solve the problem following this answer and now I can download the zip file, just for the record:

I modified the server code, had to open the file as binary and encode it to base64:

with open(f"user_projects/delivery.zip", mode="rb") as binaryFile:
        binaryFile = binaryFile.read()
        archivoEnBase64 = base64.b64encode(binaryFile)

return archivoEnBase64

Here's the modified JS code:

var zipFile = new Blob([atob(this.response)], {"type": "application/zip"})               
            var url = URL.createObjectURL(zipFile)

            downloadLink.href = "data:application/zip;base64," + this.response;

The request response is a byte string so I decoded it with atob() and the href attribute uses the data URI scheme:

data:[media type][;base64],data

Alex
  • 139
  • 6