I am trying to add new feature to my web application, to make file uploads avaliable.
Tech: Flask, Python 3. I am using ajax an object FormData, but it doesn't work. Can’t send file to server.
Function ajax() in javascript causes error 400.I have tried to add a form in html and to use FormData(form). But it didn't change anything.
html
<label for="new-homework" class="add">Add</label>
<button class="send">Submit</button>
<input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files">
javascript
function ajax(type, url, data, callback) {
var f = callback || function (data) {};
var request = new XMLHttpRequest();
request.onreadystatecheng = function () {
if(request.readyState == 4 && request.status == 200){
console.log('Success');
}
}
request.open(type, url);
if(type == 'POST')
request.setRequestHeader('Content-type','application/json; charset=utf-8');
console.log(data);
request.send(data); // Issue is here
}
var nf_button = document.getElementById("new-homework");
nf_button.addEventListener("change", function() {
console.log('working');
var files = nf_button.files;
canSendFiles(files);
}, false);
function canSendFiles(files) {
document.querySelector('button.send').onclick = function () {
var form = new FormData();
form.append('homework', files);
console.log(form.getAll('homework'));
ajax('POST', '/upload_file', form, function () {
console.log('Sent');
});
}
}
python
UPLOAD_FOLDER = "C:\chess_school\pa\saved"
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif',
'TXT', 'PDF', 'PNG', 'JPG', 'JPEG', 'GIF']
)
@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
"""
Files upload
:return:
"""
if request.method == 'POST':
file = request.files['file']
print(file)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
path = app.config['UPLOAD_FOLDER']
if not os.path.exists(path):
os.makedirs(path)
file.save(os.path.join(path, filename))
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
What's wrong? How to fix it?
Any help will be appreciated!