The solution given here helps in uploading files asynchronously.
When I change it to include both the files and some string data I'm unable to access both the string and the files.
This is what I have so far:
<body>
<h4>Select files to be uploaded</h4>
<br/>
<form id="upload-form" method="post" enctype="multipart/form-data">
<p><input type="file" multiple="" name="files" id="files"></p>
<p><input type="button" class="btn" id="upload-file-btn" value="Upload" /></p>
</form>
</body>
<script type="text/javascript">
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-form')[0])
console.log(form_data)
console.log('Starting upload')
$.ajax({
type: 'POST',
url: '/upload',
data: { form_data: form_data,
path: 'test_folder_2/'
},
contentType: false,
cache: false,
processData: false,
async: false,
success: function(data) {
console.log('Success')
},
error: function() {
console.log('Error')
}
});
});
});
</script>
This is my view on the server:
@app.route('/upload', methods=['POST'])
def upload_file():
path = request.form.get('path')
print("PATH: ", path)
path = path or 'test_folder_2/' # Fallback
if request.method == 'POST':
files = request.files.getlist('files')
print("FILES: ", files)
filenames = [_ for _ in os.listdir(os.path.join('.', 'content', path ))]
for file in files:
if file and helpers.is_allowed_file(file.filename):
filename = helpers.get_name(file.filename, filenames)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], path, filename))
return 'Done'
The output of this is:
PATH: None
FILES: []
I tried JSON.stringify() to send the data, but the files don't seem to be arriving to the server on doing that.
FWIW this is what I'm trying to do: Receive a bunch of files from the client and store it in the file specified by the "path".