Permission denied on deployed Flask app file upload using AJAX
ajax, flask, python
Solution
You are saving a file with no path information. This means it'll be saved in the current working directory, wherever that may be for the Apache process. You do not have write permissions there. This working directory is almost certainly not the same place as where your project code is stored.
Specify a path for the file. You could use a directory based on the current module (`os.path.dirname(__file__)` is the directory of the current module), or configure a destination path for your application.
You may want to study the Uploading Files pattern in this context.
Problem
My file upload was working perfectly on the built in Flask server, but the file upload broke when I deployed it (Apache2). Flask python code: ``` @app.route('/uploadajax', methods=['POST', 'GET']) def upload(): file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save('TEST.pdf') return jsonify({'filename':'http://www.michigan.gov/documents/sprsConnectionsVol5No1_15852_7.pdf'}) ``` Javascript: ``` $(function() { $('#upload-file-btn').click(function() { var form_data = new FormData($('#upload-file')[0]) $.ajax({ type: 'POST', url: SCRIPT_ROOT + '/uploadajax', data: form_data, contentType: false, cache: false, processData: false, async: false, success: function(data) { console.log('Loaded questions successfully.') packet_frame = '<iframe src="http://docs.google.com/viewer?url=' + encodeURI(data['filename']) + '&embedded=true" width="100%" height="260" style="border: none;"></iframe>' } }) }) }) ``` There's no error if I comment out the file.save('...') line. The specific error is ``` [Sat Nov 30 20:43:21 2013] [error] [client 66.75.0.4] file.save('TEST.pdf'), referer: http://mydomain.com/ [Sat Nov 30 20:43:21 2013] [error] [client 66.75.0.4] File "/usr/local/lib/python2.6/dist-packages/werkzeug/datastructures.py", line 2576, in save, referer: http://mydomain.com/ [Sat Nov 30 20:43:21 2013] [error] [client 66.75.0.4] dst = open(dst, 'wb'), referer: http://mydomain.com/ [Sat Nov 30 20:43:21 2013] [error] [client 66.75.0.4] IOError: [Errno 13] Permission denied: 'TEST.pdf', referer: http://mydomain.com/ ``` I thought that this wouldn't happen because I'm only writing to a subdirectory and not root, but there's still the permission denied error. Any help?