douluozhan4370 2016-04-04 09:32
浏览 28
已采纳

too long

I've been trying to get a file-upload working for a website I'm working on. I'm doing this outside of a form, and after days of searching I finally found something that fits my method from the answer on this question:

The thing is, as soon as I applied the code to my own script, I got 'Undefined index' errors, and when I removed it, everything went fine.

Here is my code:

HTML

<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>

jQuery

function newsItem(action){
    var thumbnail = $('#newsitem-thumbnail')[0].files[0];
    var fileReader = new FileReader();
    fileReader.readAsText(thumbnail, 'UTF-8');
    fileReader.onload = shipOff;

    function shipOff(e){
        var r = e.target.result;
        if(action == "insert"){
            $.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
                                              thumbnail:thumbnail.name,
                                              action:action,
                                              data:r},
            function(result){
                console.log(result);
                console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
                if(result == "succes"){
                    window.location.reload();
                }else{
                    $(".error-msg").html(result);
                }
            });
        }else if(action == "delete"){
            //To be implemented when I get the submit working D:
        }
    }
}

PHP (Please excuse the mess -needs serious cleaning)

<?php
    include("../assets/libs/SQLLib.php");
    DB_Connect("test");

    echo print_r($_POST);
    echo var_dump($_POST);
    $message = $_POST['message'];
    $action = $_POST['action'];
    $thumbnail = $_POST['thumbnail'];
    $data = $_POST['data'];

    $serverFile = time().$thumbnail;
    $fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
    fwrite($fp, $data);
    fclose($fp);
    $returnData = array("serverFile" => $serverFile);
    echo json_encode($returnData);

    if($_POST['message'] != ""){
        $canPost = true;
    }else{
        echo "The message can not be empty.";
    }

    if($action == "insert" && $canPost){
        $sql = "insert into newsitems
                (date, message, thumbnail)
                values
                (NOW(),'".$message."', '".$thumbnail."')";
        $result = mysql_query($sql);
        if(!$result){
            echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
        }else{
            echo "succes";
        }
    }else if($action == "delete"){
        $sql = "";
    }
?>

Does anybody see what's going wrong here? Or does anyone have an alternative option?

I hope someone can help me out with this issue.

  • 写回答

3条回答 默认 最新

  • duanchuang1935 2016-04-06 06:59
    关注

    So in the end I opted out of a full jQuery-upload, and went for something else. I am now uploading files purely through a PHP call, instead of a jQuery post event, with a small JavaScript check next to it to see if the form is submittable.

    The code:

    HTML

    <div class='error-msg'></div>
    <form method='post' action='requestPages/newsitems.php' enctype='multipart/form-data'>
        News message
        <textarea id='newsitem-message' name='newsitem-message' onchange='checkFormSubmit()'/>
        <input type='file' name='newsitem-thumbnail' id='newsitem-thumbnail' />
        <input hidden type='text' value='insert' name='newsitem-action'/>
        <input class='submit' id='newsitem-submit' type='submit' value='Post news' disabled/>
    </form>
    

    PHP

    <?php
    include("../assets/libs/SQLLib.php");
        DB_Connect("test");
    
        var_dump($_FILES);
    var_dump($_POST);
    
    $message = $_POST['newsitem-message'];
    $action = $_POST['newsitem-action'];
    $errors= array();
    $hasFile = false;
    
    if($action == "insert"){
        echo ($_FILES['newsitem-thumbnail'][0] == UPLOAD_ERR_NO_FILE);
        if(isset($_FILES['newsitem-thumbnail']) && $_FILES['newsitem-thumbnail']['error'] != UPLOAD_ERR_NO_FILE){
            $file_name = $_FILES['newsitem-thumbnail']['name'];
            $file_size =$_FILES['newsitem-thumbnail']['size'];
            $file_tmp =$_FILES['newsitem-thumbnail']['tmp_name'];
            $file_type=$_FILES['newsitem-thumbnail']['type'];
            $file_ext=strtolower(end(explode('.',$_FILES['newsitem-thumbnail']['name'])));
    
            $extensions= array("jpeg","jpg","png");
    
            if(!in_array($file_ext,$extensions)){
                $errors[]="extension not allowed, please choose a JPEG or PNG file.";
            }
            $hasFile = true;
        }
        if(empty($errors)){
            $sql = "insert into newsitems
                    (date, message, thumbnail)
                    values
                    (NOW(),'".$message."', '".$file_name."')";
            $result = mysql_query($sql);
            if(!$result){
                echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
            }else{
                if($hasFile){
                    if(!move_uploaded_file($file_tmp,"../assets/images/thumbnails/".$file_name)){
                        echo "Moving the file failed!";
                    }
                }
            }
        }else{
            print_r($errors);
        }
    }else if($action == "delete"){
        $sql = "";
    }
    ?>
    

    JavaScript

    function checkFormSubmit(){
        if($.trim($('#newsitem-message').val()) != ""){
            $('#newsitem-submit').prop('disabled', false);
        }else{
            $('#newsitem-submit').prop('disabled', true);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)