我可以用 jquery ajax 和 php 上传文件,需要一些解释和修改

I can upload files with jquery ajax and php, some explaination and modification required

我读过这个。

https://developer.mozilla.org/en/docs/Web/API/FormData

仍然无法理解为什么代码中的 formdata(frm) 为空。 console.log(frm); returns "FormData{}" 空。为什么?

file_form.php =>

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src="" />
<img id="my_image2" src="" />

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

    $(document).ready(function (e) {
        $("#uploadForm1").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            console.log(frm);
            e.preventDefault();
            $.ajax({
                url: "upload_script1.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl1 = "uploads/" + JsonObject.image1;
                    $("#my_image1").attr("src", fl1).height(100).width(100);
                }
            });
        }));

        $("#uploadForm2").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            e.preventDefault();
            $.ajax({
                url: "upload_script2.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl2 = "uploads/" + JsonObject.image2;
                    $("#my_image2").attr("src", fl2).height(100).width(100);
                }
            });
        }));


    });
</script>

upload_script1.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);

    $image1 = $_FILES['image1']['name'];
    $images["image1"] = $image1;
    echo json_encode($images);
?>

upload_script2.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['image2']['name']);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile);
    $image2 = $_FILES['image2']['name'];
    $images["image2"] = $image2;
    echo json_encode($images);
?>
  1. 任何人都可以将两个 $.ajax() 代码重写为一个 $.ajax() 代码以缩短代码吗?如有必要,重写 html 和 php 代码。

我们将不胜感激任何帮助。 提前致谢。

我只修改了javascript部分。

我的例子是...

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src=""/>
<img id="my_image2" src=""/>

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

function fetch( type ) {

    var typeMap = {
        form1: { formId: 'uploadForm1', url: 'upload_script1.php', flKey: 'image1', imgId: 'my_image1' },
        form2: { formId: 'uploadForm2', url: 'upload_script2.php', flKey: 'image2', imgId: 'my_image2' }
    };

    var info = typeMap[ type ];
    if( ! info ) return console.error('no type: ' + type );

    $("#"+info.formId).on('submit',(function(e) {

        frm = new FormData($(this)[0]);
        console.log(frm);
        e.preventDefault();
        $.ajax({
            url: info.url,
            type: "POST",
            data:  frm,
            contentType: false,
            cache: false,
            processData:false,
            success: function(response){                
                var JsonObject = JSON.parse(response);              
                $("#targetLayer").html(response);

                var fl = "uploads/" + JsonObject[ info.flKey ];
                $("#"+info.imgId).attr("src",fl).height(100).width(100);
            }           
       });
    }));
}

$(document).ready(function (e) {    
    fetch( 'form1' );
    fetch( 'form2' );
});

</script>

您的 FormData 对象可能显示为空,因为您的浏览器不支持 iterators

查看方法 compatibility table at MDN。在内部,控制台可能会尝试使用 entries 方法公开的迭代器来枚举属性。

我在 Chromium 45 中得到了相同的结果。


至于简化代码,您可以通过参数化来合并函数和 PHP 脚本。

function createFormHandler($form, url, $image) {
  $form.on('submit', function(e) {
    var frm = new FormData($form[0]);
    e.preventDefault();

    $.ajax({
      url: url,
      type: "POST",
      data: frm,
      contentType: false,
      cache: false,
      processData: false,
      success: function(response) {                
        var JsonObject = JSON.parse(response);              
        $("#targetLayer").html(response);
        var src = "uploads/" + JsonObject.image1;
        $image.attr("src", src).height(100).width(100);
      }           
    });
  });
}

createFormHandler($('#uploadForm1'), 'upload_script.php?id=1', $('#my_image1'));
createFormHandler($('#uploadForm2'), 'upload_script.php?id=2', $('#my_image2'));

现在每个表单的数字 ID 都表示为一个 URL 参数,而不必是一个单独的脚本。您可以合并两个 PHP 文件并改用一个 upload_script.php

<?php
  $id = $_GET['id'];
  $uploaddir = '/var/www/html/file-upload/uploads/';
  $uploadfile = $uploaddir . basename($_FILES['image']['name']);
  move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile);

  $image = $_FILES['image']['name'];
  $images["image" . $id] = $image;
  echo json_encode($images);
?>

这也让您规范化输入名称。

<form id="uploadForm1" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>

<form id="uploadForm2" enctype="multipart/form-data">
  <input name="image" type="file" />
  <input type="submit" value="Submit" />
</form>
I think it will minimize your code

<title>Upload File</title>
<div id="targetLayer">No Image</div>
<img id="my_image1" src="" />
<img id="my_image2" src="" />

<form id="uploadForm1" enctype="multipart/form-data">
    <input name="image1" type="file" />
    <input name="image2" type="file" />
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript" src="jquery-1.11.3.js"></script>

<script type="text/javascript">

    $(document).ready(function (e) {
        $("#uploadForm1").on('submit', (function (e) {
            frm = new FormData($(this)[0]);
            console.log(frm);
            e.preventDefault();
            $.ajax({
                url: "upload_script1.php",
                type: "POST",
                data: frm,
                contentType: false,
                cache: false,
                processData: false,

                success: function (response) {
                    var JsonObject = JSON.parse(response);
                    $("#targetLayer").html(response);

                    var fl1 = "uploads/" + JsonObject.image1;
                    $("#my_image1").attr("src", fl1).height(100).width(100);
                     $("#my_image2").attr("src", fl2).height(100).width(100);
                }
            });
        }));



    });
</script>

upload_script1.php =>

<?php
    $uploaddir = '/var/www/html/file-upload/uploads/';

    $uploadfile = $uploaddir . basename($_FILES['image1']['name']);
     $uploadfile2 = $uploaddir . basename($_FILES['image2']['name']);     
    move_uploaded_file($_FILES['image1']['tmp_name'], $uploadfile);
    move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile2);
    $image1 = $_FILES['image1']['name'];
    $image2 = $_FILES['image2']['name'];
    $images["image1"] = $image1;
     $images["image2"] = $image2;
    echo json_encode($images);
?>