【问题标题】:How to upload an image to server directory using ajax?如何使用 ajax 将图像上传到服务器目录?
【发布时间】:2021-12-07 00:44:03
【问题描述】:

我有这个 ajax 发布到服务器以将一些数据发送到 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

如何在此 ajax 帖子中包含图像(来自 #myFileInput)并使用 php 中的相同查询将其保存到服务器?

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

【问题讨论】:

  • 我猜“现代”方法是将Fetch api与FormData对象结合使用
  • 请注意,您的代码易受 SQL 注入攻击,您可能希望进行的另一项更改是开始使用 prepared statements
  • 要在 ajax 中上传文件,请使用 FormData (我想如果你用谷歌搜索“ajax 文件上传”你会得到很多例子)

标签: javascript php jquery ajax fetch-api


【解决方案1】:

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

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

【讨论】:

  • 请格式化您的代码以使其更具可读性。
  • 上述发送文件和文本框中输入的数据。
【解决方案2】:

您应该使用 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']);
    }

?>

【讨论】:

  • 这只会发送文件,不会发送其他字段。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2018-08-24
    • 2021-01-18
    相关资源
    最近更新 更多