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

如何将文件从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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度