Я пытаюсь добавить фото профиля своим пользователям, но когда я пытаюсь нажать кнопку «Отправить», она не проходит. < /p>
Вот мой json < /p>
function getUserFormData(form) {
return {
action: "addUser",
user: {
user_id: User : null,
email: form['email'].value,
username: form['username'].value,
password: Util.hash(form['password'].value),
password_confirmation: Util.hash(form['password_confirmation'].value),
profile_image: form['profile_image'].value
}
};
}
AS.Http.submituser = function (form, data, success, error, complete) {
AS.Util.removeErrorMessages();
var $submitBtn = $(form).find("button[type=submit]");
var $fileupload = $(data).prop('profile_image');
var formData = new FormData();
formData.append('file', $fileupload);
if ($submitBtn) {
AS.Util.loadingButton($submitBtn, $submitBtn.data('loading-text') || $_lang.working);
}
$.ajax({
url: "/Ajax.php",
cache: false,
contentType: false,
processData: false,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
form.reset();
if (typeof success === "function") {
success(response);
}
},
error: error || function (errorResponse) {
AS.Util.showFormErrors(form, errorResponse);
},
complete: complete || function () {
if ($submitBtn) {
AS.Util.removeLoadingButton($submitBtn);
}
}
});
};
< /code>
Вот задний конец < /p>
public function add(array $data)
{
if ($errors = $this->registrator->validateUser($data, false)) {
ASResponse::validationError($errors);
}
// Handle secure profile image upload
$files = $data['profile_image'];
$targetDirectory = "../assets/img/usersprofile/";
$imageFileType = strtolower(pathinfo($files["profile_image"]["name"], PATHINFO_EXTENSION));
// Generate a unique image filename: complete_name_uniqueID.extension
$username = $data['username'];
$safeName = preg_replace('/[^A-Za-z0-9]/', '_', $username); // Remove special chars
$uniqueID = uniqid();
$imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
$targetFile = $targetDirectory . $imageName;
// Validate image file
$validMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$check = getimagesize($files["profile_image"]["tmp_name"]);
if ($check === false || !in_array($check['mime'], $validMimeTypes)) {
throw new Exception("Invalid image file format.");
}
// Check file size (max 2MB)
if ($files["profile_image"]["size"] > 2000000) {
throw new Exception("File size exceeds the 2MB limit.");
}
// Restrict executable file uploads
if (preg_match('/\.(php|html|htm|js|exe|sh)$/i', $files["profile_image"]["name"])) {
throw new Exception("Invalid file type.");
}
// Ensure upload directory is safe
if (!is_dir($targetDirectory) && !mkdir($targetDirectory, 0755, true)) {
throw new Exception("Failed to create upload directory.");
}
// Move uploaded file
if (!move_uploaded_file($files["profile_image"]["tmp_name"], $targetFile)) {
throw new Exception("Error uploading the image.");
}
$this->db->insert('users', [
'email' => $data['email'],
'username' => $data['username'],
'password' => $this->hashPassword($data['password']),
'profile_image' => $imageName
]);
Response::success(["message" => trans("user_added_successfully")]);
}
< /code>
Я попытался добавить файл, но, к сожалению, все еще ничего не происходит. Я не вижу, что такое ошибка, потому что она не показывает.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... ng-through
Когда я отправляю FormData, используя JSON/AJAX, это не проходит ⇐ Jquery
Программирование на jquery
-
Anonymous
1756192066
Anonymous
Я пытаюсь добавить фото профиля своим пользователям, но когда я пытаюсь нажать кнопку «Отправить», она не проходит. < /p>
Вот мой json < /p>
function getUserFormData(form) {
return {
action: "addUser",
user: {
user_id: User : null,
email: form['email'].value,
username: form['username'].value,
password: Util.hash(form['password'].value),
password_confirmation: Util.hash(form['password_confirmation'].value),
profile_image: form['profile_image'].value
}
};
}
AS.Http.submituser = function (form, data, success, error, complete) {
AS.Util.removeErrorMessages();
var $submitBtn = $(form).find("button[type=submit]");
var $fileupload = $(data).prop('profile_image');
var formData = new FormData();
formData.append('file', $fileupload);
if ($submitBtn) {
AS.Util.loadingButton($submitBtn, $submitBtn.data('loading-text') || $_lang.working);
}
$.ajax({
url: "/Ajax.php",
cache: false,
contentType: false,
processData: false,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
form.reset();
if (typeof success === "function") {
success(response);
}
},
error: error || function (errorResponse) {
AS.Util.showFormErrors(form, errorResponse);
},
complete: complete || function () {
if ($submitBtn) {
AS.Util.removeLoadingButton($submitBtn);
}
}
});
};
< /code>
Вот задний конец < /p>
public function add(array $data)
{
if ($errors = $this->registrator->validateUser($data, false)) {
ASResponse::validationError($errors);
}
// Handle secure profile image upload
$files = $data['profile_image'];
$targetDirectory = "../assets/img/usersprofile/";
$imageFileType = strtolower(pathinfo($files["profile_image"]["name"], PATHINFO_EXTENSION));
// Generate a unique image filename: complete_name_uniqueID.extension
$username = $data['username'];
$safeName = preg_replace('/[^A-Za-z0-9]/', '_', $username); // Remove special chars
$uniqueID = uniqid();
$imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
$targetFile = $targetDirectory . $imageName;
// Validate image file
$validMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$check = getimagesize($files["profile_image"]["tmp_name"]);
if ($check === false || !in_array($check['mime'], $validMimeTypes)) {
throw new Exception("Invalid image file format.");
}
// Check file size (max 2MB)
if ($files["profile_image"]["size"] > 2000000) {
throw new Exception("File size exceeds the 2MB limit.");
}
// Restrict executable file uploads
if (preg_match('/\.(php|html|htm|js|exe|sh)$/i', $files["profile_image"]["name"])) {
throw new Exception("Invalid file type.");
}
// Ensure upload directory is safe
if (!is_dir($targetDirectory) && !mkdir($targetDirectory, 0755, true)) {
throw new Exception("Failed to create upload directory.");
}
// Move uploaded file
if (!move_uploaded_file($files["profile_image"]["tmp_name"], $targetFile)) {
throw new Exception("Error uploading the image.");
}
$this->db->insert('users', [
'email' => $data['email'],
'username' => $data['username'],
'password' => $this->hashPassword($data['password']),
'profile_image' => $imageName
]);
Response::success(["message" => trans("user_added_successfully")]);
}
< /code>
Я попытался добавить файл, но, к сожалению, все еще ничего не происходит. Я не вижу, что такое ошибка, потому что она не показывает.>
Подробнее здесь: [url]https://stackoverflow.com/questions/79746516/when-i-submit-formdata-using-json-ajax-it-is-not-going-through[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия