Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
¿Cómo cargar una imagen en el directorio del servidor usando ajax?

Tengo esta publicación de ajax en el servidor para enviar algunos datos a una base de datos SQL:

 $.ajax({ method: "POST", url: "https://www.example.com/main/public/actions.php", data: { name: person.name, age: person.age, height: person.height, weight: person.weight }, success: function (response) { console.log(response) } })

en el servidor obtengo estos datos con php así:

 <?php include "config.php"; if(isset ( $_REQUEST["name"] ) ) { $name = $_REQUEST["name"]; $age = $_REQUEST["age"]; $height = $_REQUEST["height"]; $weight = $_REQUEST["weight"]; $sql = "INSERT INTO persons ( name, age, height, weight ) VALUES ( '$name', '$age', '$height', '$weight' )"; if ($conn->query($sql) === TRUE) { echo "New person stored succesfully !"; exit; }else { echo "Error: " . $sql . "<br>" . $conn->error; exit; } }; ?>

También tengo esta entrada:

 <input id="myFileInput" type="file" accept="image/*">

y en el mismo directorio que actions.php tengo la carpeta /images

¿Cómo puedo incluir una imagen (de #myFileInput ) en esta publicación de ajax y guardarla en el servidor usando la misma consulta en php?

He buscado soluciones en SO, pero la mayoría tiene más de 10 años. Me preguntaba si existe un método simple y moderno para hacerlo. Estoy abierto a aprender y usar la API de búsqueda si es la mejor práctica.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

a través de ajax FormData puede enviarlo. consulte aquí. Nota: datos: nuevo FormData (este): esto envía los datos completos del formulario (incluidos los datos del archivo y del cuadro de entrada)

URL: https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/

 $(document).ready(function(e) { $("#form").on('submit', (function(e) { e.preventDefault(); $.ajax({ url: "ajaxupload.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData: false, beforeSend: function() { //$("#preview").fadeOut(); $("#err").fadeOut(); }, success: function(data) { if (data == 'invalid') { // invalid file format. $("#err").html("Invalid File !").fadeIn(); } else { // view uploaded file. $("#preview").html(data).fadeIn(); $("#form")[0].reset(); } }, error: function(e) { $("#err").html(e).fadeIn(); } }); })); });
about 4 years ago · Juan Pablo Isaza Report

0

Debe usar la API formData para enviar su archivo (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData )

Creo que lo que buscas es algo así:

 var file_data = $('#myFileInput').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajax({ url: 'https://www.example.com/main/public/actions.php', contentType: false, processData: false, // Important to keep file as is data: form_data, type: 'POST', success: function(php_script_response){ console.log(response); } });

jQuery ajax wrapper tiene un parámetro para evitar el procesamiento de contenido que es importante para la carga de archivos.

En el lado del servidor, un controlador simple de vrey para archivos podría verse así:

 <?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error']; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); } ?>
about 4 years ago · Juan Pablo Isaza Report

0

Si no es reacio a usar la API de fetch , es posible que pueda enviar los datos de texto y su archivo de esta manera:

 let file=document.querySelector('#myFileInput').files[0]; let fd=new FormData(); fd.set('name',person.name); fd.set('age',person.age); fd.set('height',person.height); fd.set('weight',person.weight); fd.set('file', file, file.name ); let args={// edit as appropriate for domain and whether to send cookies body:fd, mode:'same-origin', method:'post', credentials:'same-origin' }; let url='https://www.example.com/main/public/actions.php'; let oReq=new Request( url, args ); fetch( oReq ) .then( r=>r.text() ) .then( text=>{ console.log(text) });

Y en el lado de PHP, debe usar una declaración preparada para mitigar la inyección de SQL y debería poder acceder al archivo cargado de esta manera:

 <?php if( isset( $_POST['name'], $_POST['age'], $_POST['height'], $_POST['weight'], $_FILES['file'] )) { include 'config.php'; $name = $_POST['name']; $age = $_POST['age']; $height = $_POST['height']; $weight = $_POST['weight']; $obj=(object)$_FILES['file']; $name=$obj->name; $tmp=$obj->tmp_name; move_uploaded_file($tmp,'/path/to/folder/'.$name ); #add file name to db???? $sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )'; $stmt=$conn->prepare($sql); $stmt->bind_param('ssss',$name,$age,$height,$weight); $stmt->execute(); $rows=$stmt->affected_rows; $stmt->close(); $conn->close(); exit( $rows ? 'New person stored succesfully!' : 'Bogus...'); }; ?>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!