duanchuonong5370 2017-08-19 06:40
浏览 76
已采纳

如何将文件从javascript上传到php服务器?

How to upload image or other file from javascript to php server ??? i am working on php api how to send and receive please help me i am getting josn data using

$login = file_get_contents('php://input');

i want to upload image using js and receive using php and upload to server disk Here is my login.php file

  <?php
session_start();
//server accpet response in forllowing format 
//{"username":"administrator","password":"administrator","remind":"on"}
// iuncluding function file
require_once "../includes/system.php";
    if(isset($_COOKIE['COOKIE_KEEP_ME_NAME1shpingcart'])){
            $_SESSION['login_usershoping'] =  $_COOKIE['COOKIE_KEEP_ME_NAME1shpingcart'];
        }   
   if(isset($_SESSION['login_usershoping'])){
    $success['alreadylogin'] = "true";
    echo $successlogin = malik_encode($success );
    die();
}
// get value
$login = file_get_contents('php://input');
    if(empty($login)){
        $error['error'] = "Username & password never be empty";
        echo $errorlogin = malik_encode($error );
        die();
    }
//decode and convert into assos array by using custom function
$login_decode = malik_decode($login,true);
    $username =  $login_decode['username'];
    $password =  $login_decode['password'];
    $remind = $login_decode['remind'];

    $db = malik_database_connection();
    $connected = null;   
    $username = $db->quote($username);
        $select = $db->query("SELECT * FROM users WHERE username=$username");
        if($select->rowCount() > 0){
            $user = $select->fetch();
            $ban = $user['ban'];
              if($ban === 'yes'){
                 $error['error'] = "Your account is banned by our admistrator";
                 echo $banerror = malik_encode($error );
              }         
            if (password_verify($password, $user["password"])){
                if(isset($remind) && $remind === 'on'){
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME1shpingcart',$user['salts'] ,time() + (86400 * 30 * 12), '/',false,true);
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME2',malik_ramdomstring_generator(60) ,time() + (86400 * 30 * 12), '/',false,true);
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME3',malik_ramdomstring_generator(50) ,time() + (86400 * 30 * 12), '/',false,true);
                }   
                $se= $_SESSION['login_usershoping'] =  $user['salts'];
                 $success['success'] = "true";
                 echo $loginsuccess = malik_encode($success );
                exit();

            }else {
                $connected = false;
            }
            }else{
            $connected = false;
        }
           if ($connected === false): 
           $error['error'] = "Username and password wrong";
            echo $loginerror = malik_encode($error );
         $connected = null; 
       endif; 
  • 写回答

1条回答 默认 最新

  • dsm17496 2017-08-19 07:55
    关注

    upload.html:

        <!DOCTYPE html>
    <html lang="en">
        <head>
            <!-- Required meta tags -->
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        </head>
        <body>
            <form id="uploadform">
                <input type="file" name="file"/><br/>
                <button type="submit">
                    Upload!
                </button>
            </form>
        </body>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
        <script>
    
            $("form#uploadform").submit(function () {
                var formData = new FormData(this);
    
                $.ajax({
                    url: '/upload_file.php',
                    type: 'POST',
                    data: formData,
                    async: false,
                    success: function (data) {
                        alert(data)
                    },
                    error:function(data){
                        alert(data);
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
    
                return false;
            });
        </script>
    </html>
    

    upload_file.php:

    /*
     * Do your authentication logic here, log in user, etc.
     */
    
    //Fist, check if we have any file sent to the script:
    $file = isset($_FILES['file']) ? $_FILES['file'] : NULL;
    
    
    //It seems we have a file?
    $tmpfile = $file['tmp_name'];
    //Find the file extension:
    $fileparts = explode('.', $file['name']);
    
    //Apply the extension, usually the last item in the parts array:
    $fileExtension = $fileparts[count($fileparts) - 1];
    
    //Make a filename:
    $filename = md5($file['name']);
    
    //add file extension to the filename:
    $filename .= '.' . $fileExtension;
    
    //Save to current directory:
    $saveto = __DIR__ . DIRECTORY_SEPARATOR . $filename;
    
    //Move file:
    move_uploaded_file($tmpfile, $saveto);
    
    ///If we ever get here, the file has been uploaded, saved and moved to the permanent location
    print 'File saved to: ' . $saveto;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀