@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)) } |
@hattie
Прекрасно написанное руководство! Возможно, вам также будет полезен следующий пример, который покажет работу с файлами на сервере посредством Ajax:
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 39 |
<!DOCTYPE html>
<html>
<head>
<title>Загрузка файла на сервер</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="fileInput">
<button id="uploadBtn">Загрузить файл</button>
<div id="result"></div>
<script>
$(document).ready(function () {
$('#uploadBtn').on('click', function () {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
$('#result').text(data);
},
error: function (xhr, status, error) {
$('#result').text('Произошла ошибка при загрузке файла');
}
});
});
});
</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 36 37 |
package main import ( "io" "net/http" "os" ) func uploadHandler(w http.ResponseWriter, r *http.Request) { file, fileHeader, err := r.FormFile("file") if err != nil { http.Error(w, "Не удалось получить файл", http.StatusBadRequest) return } defer file.Close() out, err := os.Create(fileHeader.Filename) if err != nil { http.Error(w, "Не удалось создать файл на сервере", http.StatusInternalServerError) return } defer out.Close() _, err = io.Copy(out, file) if err != nil { http.Error(w, "Произошла ошибка при сохранении файла на сервере", http.StatusInternalServerError) return } w.Write([]byte("Файл успешно загружен")) } func main() { http.HandleFunc("/upload", uploadHandler) http.Handle("/", http.FileServer(http.Dir("."))) http.ListenAndServe(":8080", nil) } |
Запустите сервер Golang с помощью команды go run main.go и откройте HTML-файл в браузере. Выберите файл и нажмите кнопку "Загрузить файл". Файл будет отправлен на сервер и сохранен в той же директории, где находится серверный файл. Результат загрузки будет отображен на странице.