如何使用ajax上传图像到服务器目录?



我有这个ajax post到服务器发送一些数据到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)
}
})

服务器中的我用PHP这样获取数据

<?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;
}

};
?>

我也有这样的输入:

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

在与actions.php相同的目录下有文件夹/images

我怎么能包括一个图像(从#myFileInput)在这个ajax帖子和保存到服务器使用相同的查询在php ?

我已经在SO中搜索了解决方案,但其中大多数都是>10岁了,我想知道是否有一个简单而现代的方法来做到这一点,我愿意学习和使用fetch api,如果它是最佳实践。

你应该使用formData API发送你的文件(https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)

我想你要找的是这样的东西:

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包装器有一个参数来避免内容处理,这对文件上传很重要。

在服务器端,一个非常简单的文件处理程序如下所示:

<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

通过ajax FormData你可以发送它。参考这里。注:data: new FormData(this) -这发送整个表单数据(包括文件和输入框数据)

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();
}
});
}));
});

如果您不反对使用fetchapi,那么您可以像这样发送文本数据和文件:

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)
});

在PHP端,你应该使用一个准备好的语句来减少SQL注入,并且应该能够像这样访问上传的文件:

<?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...');
};
?>

最新更新