4

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?

Zrufy
  • 423
  • 9
  • 22
  • Are you sure your `name` is a correct path, either relative to the python-script or an absolute one? It's easier to use an absolute path. In your app's config you can specify something like `basedir = os.path.abspath(os.path.dirname(__file__))` and then use it for static files paths like that: `STATIC_DIR = os.path.join(basedir, 'app/static')`. And eventually when manipulating files you do something like this: `os.remove(os.path.join(app.config['STATIC_DIR'], name))` – vrs Apr 25 '16 at 10:18
  • @vrs I also thought I to this error. So I directly inserted os.remove command ( "static / document / name_file") and even so I deleted it. I thought it was the download command embedded in JavaScript. Why the link appears so: download>Download But even this. I do not know how to do. – Zrufy Apr 25 '16 at 10:30
  • @Bigzil post it as an answer and accept it, so that other people with the same problem could easily find solution. – vrs Jul 11 '16 at 07:59

1 Answers1

9

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)
fkaralis
  • 445
  • 1
  • 6
  • 10
Zrufy
  • 423
  • 9
  • 22