简体   繁体   English

jQuery AJAX 文件上传 PHP

[英]jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.我想在我的 Intranet 页面中实现一个简单的文件上传,尽可能使用最小的设置。

This is my HTML part:这是我的 HTML 部分:

<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>

and this is my JS jquery script:这是我的 JS jquery 脚本:

$("#upload").on("click", function() {
    var file_data = $("#sortpicture").prop("files")[0];   
    var form_data = new FormData();
    form_data.append("file", file_data);
    alert(form_data);
    $.ajax({
        url: "/uploads",
        dataType: 'script',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(){
            alert("works"); 
        }
    });
});

There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".在网站的根目录下有一个名为“uploads”的文件夹,具有“users”和“IIS_users”的更改权限。

When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]".当我选择带有文件格式的文件并按下上传按钮时,第一个警报返回“[object FormData]”。 the second alert doesn't get called and the"uploads" folder is empty too!?第二个警报没有被调用,并且“上传”文件夹也是空的!?

Can someone help my finding out whats wrong?有人可以帮我找出问题所在吗?

Also the next step should be, to rename the file with a server side generated name.下一步应该是用服务器端生成的名称重命名文件。 Maybe someone can give me a solution for this, too.也许有人也可以给我一个解决方案。

You need a script that runs on the server to move the file to the uploads directory.您需要在服务器上运行的脚本将文件移动到上传目录。 The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload. jQuery ajax方法(在浏览器中的客户端上运行)将表单数据发送到服务器,然后在服务器上运行的脚本处理上传。

Your HTML is fine, but update your JS jQuery script to look like this:你的 HTML 很好,但更新你的 JS jQuery 脚本看起来像这样:

(Look for comments after // <-- ) (在// <--之后查找注释)

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // <-- point to server-side PHP script 
        dataType: 'text',  // <-- what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // <-- display response from the PHP script, if any
        }
     });
});

And now for the server-side script, using PHP in this case.现在对于服务器端脚本,在这种情况下使用PHP

upload.php : a PHP script that is located and runs on the server, and directs the file to the uploads directory: upload.php :位于服务器上并在服务器上运行的 PHP 脚本,并将文件定向到上传目录:

<?php

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

?>

Also, a couple things about the destination directory:另外,关于目标目录的一些事情:

  1. Make sure you have the correct server path , ie, starting at the PHP script location what is the path to the uploads directory, and确保您有正确的服务器路径,即从 PHP 脚本位置开始,上传目录的路径是什么,以及
  2. Make sure it's writeable .确保它是可写的。

And a little bit about the PHP function move_uploaded_file , used in the upload.php script:还有一点关于在upload.php脚本中使用的 PHP 函数move_uploaded_file

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. $_FILES['file']['name']是文件上传时的名称。 You don't have to use that.你不必使用它。 You can give the file any name (server filesystem compatible) you want:你可以给文件任何你想要的名字(服务器文件系统兼容):

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either.最后,请注意您的 PHP upload_max_filesizepost_max_size配置值,并确保您的测试文件不超过任何一个。 Here's some help how you check PHP configuration and how you set max filesize and post settings .这里有一些帮助您如何检查 PHP 配置以及如何设置最大文件大小和发布设置

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

Use pure js使用纯js

 async function saveFile() { let formData = new FormData(); formData.append("file", sortpicture.files[0]); await fetch('/uploads', {method: "POST", body: formData}); alert('works'); }
 <input id="sortpicture" type="file" name="sortpic" /> <button id="upload" onclick="saveFile()">Upload</button> <br>Before click upload look on chrome>console>network (in this snipped we will see 404)

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'.文件名自动包含在请求中并且服务器可以读取它,“内容类型”自动设置为“多部分/表单数据”。 Here is more developed example with error handling and additional json sending这是带有错误处理和附加 json 发送的更发达的示例

 async function saveFile(inp) { let user = { name:'john', age:34 }; let formData = new FormData(); let photo = inp.files[0]; formData.append("photo", photo); formData.append("user", JSON.stringify(user)); try { let r = await fetch('/upload/image', {method: "POST", body: formData}); console.log('HTTP response code:',r.status); alert('success'); } catch(e) { console.log('Huston we have problem...:', e); } }
 <input type="file" onchange="saveFile(this)" > <br><br> Before selecting the file Open chrome console > network tab to see the request details. <br><br> <small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
    url: "upload.php",
    type: "POST",
    data : formData,
    processData: false,
    contentType: false,
    beforeSend: function() {

    },
    success: function(data){




    },
    error: function(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});

and this is the php file to receive the uplaoded files这是接收上传文件的php文件

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.我想在我的Intranet页面上实现一个简单的文件上传,并使用最小的设置。

This is my HTML part:这是我的HTML部分:

<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>

and this is my JS jquery script:这是我的JS jQuery脚本:

$("#upload").on("click", function() {
    var file_data = $("#sortpicture").prop("files")[0];   
    var form_data = new FormData();
    form_data.append("file", file_data);
    alert(form_data);
    $.ajax({
        url: "/uploads",
        dataType: 'script',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(){
            alert("works"); 
        }
    });
});

There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".网站的根目录中有一个名为“ uploads”的文件夹,具有“用户”和“ IIS_users”的更改权限。

When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]".当我选择具有文件格式的文件并按下上载按钮时,第一个警报将返回“ [object FormData]”。 the second alert doesn't get called and the"uploads" folder is empty too!?第二个警报不会被调用,并且“ uploads”文件夹也为空!

Can someone help my finding out whats wrong?有人可以帮助我找出问题所在吗?

Also the next step should be, to rename the file with a server side generated name.下一步也应该是,使用服务器端生成的名称重命名该文件。 Maybe someone can give me a solution for this, too.也许有人也可以给我解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM