I can't send a file to the server using ajax, a FormData object. The javascript ajax function causes a 404 error. Swears at the request.send (data) line.

html

<label for="new-homework" class="add">Прикрепить</label> <button class="send">Отправить</button> <input type="file" style="visibility:hidden;" multiple id="new-homework" value="Выберите файлы"> 

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('успех'); } } request.open(type, url); if(type == 'POST') request.setRequestHeader('Content-type','application/json; charset=utf-8'); console.log(data); request.send(data); } var nf_button = document.getElementById("new-homework"); nf_button.addEventListener("change", function() { console.log('работает'); 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('запрос отправлен'); }); } } 

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(): """ АПИ для загрузки файлов на сервер :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 is the problem, how to fix it?

EDIT1

Adding a form to html and using FormData (form) does not change the situation.

  • About error 400, something was already ... as protection against some type of attack ... Find the error in the logs and show its details. Or ... try to make a test form and repeat the post through the form. - nick_n_a
  • 404 returns when sending a file or redirect after saving the file? not found usually happens because of the error of the routes - Dmitry Kozlov

0