Когда я отправляю FormData, используя JSON/AJAX, это не проходитJquery

Программирование на jquery
Ответить
Anonymous
 Когда я отправляю FormData, используя JSON/AJAX, это не проходит

Сообщение 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>
Я попытался добавить файл, но, к сожалению, все еще ничего не происходит. Я не вижу, что такое ошибка, потому что она не показывает.>

Подробнее здесь: https://stackoverflow.com/questions/797 ... ng-through
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»