Zrufy
Zrufy

Reputation: 453

Flask - delete file after download

I need some help with my code. In my site I am not able to figure out how to solve a problem. I explain the code via JavaScript creates a link that lets you download the document requested by the static folder. Doing so.

@ App.route ( '/ static / document / <path: name>', methods = [ 'POST'])
def downloads (name): #name is the name of the document
    return os.remove (name)

Then the document I take it, but the file is not deleted. This is the javascript code for download this file.

downloadlink var = document.createElement ( "a");
                        d = obj.d; # D is download method before
                        downloadlink.href = d;
                        downloadlink.className = "DOWNLOAD_LINK";
                        downloadlink.download = n;
                        downloadlink.onClick = setTimeout (function () {location.reload (true);}, 30000);
                        downloadlink.innerHTML = "<p> Download document" + n + "</ p>";
                        document.getElementById ( "results"). appendChild (downloadlink);

where am I wrong?

Upvotes: 4

Views: 5217

Answers (1)

Zrufy
Zrufy

Reputation: 453

Resolved with this code.

@app.route('/path/<name>') 
def download(name): 
   file_path ="/path/"+name
   file_handle = open(file_path, 'r')

   @after_this_request 
   def remove_file(response): 
      os.remove("/path/"+name) 
      return response 

   return send_file(file_handle)

Upvotes: 9

Related Questions