@hattie
Вот пример, как отправить файл на сервер с использованием AJAX в Golang:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form id="fileForm" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">Отправить</button> </form> <script> $(document).ready(function () { $('#fileForm').submit(function (event) { event.preventDefault(); // отменяем действие по умолчанию (отправку формы) var formData = new FormData(); // создаем объект FormData var fileInput = $('input[type="file"]')[0]; // получаем выбранный файл formData.append('file', fileInput.files[0]); // добавляем файл в FormData $.ajax({ url: '/upload', // URL сервера для загрузки файла type: 'POST', data: formData, processData: false, contentType: false, success: function (data) { // обработка успешной загрузки файла }, error: function (xhr, status, error) { // обработка ошибки загрузки файла } }); }); }); </script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package main import ( "io" "log" "net/http" "os" ) func uploadHandler(w http.ResponseWriter, r *http.Request) { file, handler, err := r.FormFile("file") // получаем файл из POST-запроса if err != nil { log.Fatal(err) } defer file.Close() f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { log.Fatal(err) } defer f.Close() // копируем содержимое файла в файловый поток _, err = io.Copy(f, file) if err != nil { log.Fatal(err) } w.Write([]byte("Файл успешно загружен")) } func main() { http.HandleFunc("/upload", uploadHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } |