如果没有附件,则发送消息,否则,刻录下载按钮 [英] If no attachment, then send message, otherwise, portray download button

查看:89
本文介绍了如果没有附件,则发送消息,否则,刻录下载按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 如果textarea有内容(不为空)且没有附件,如果textarea为空,但添加了附件,则显示 download 按钮,然后在div中显示消息。 ,这将强制消息接收者将附件保存到本地磁盘。

  2. 如果textarea不为空,并且添加了附件,则显示消息和下载按钮。 >

我现在的状况:

目前,我有以下代码片段来处理附件(目前只能是图片)。理想情况下,我不想在服务器上存储任何东西:



首先,这里是我的消息页面的可视化表示,以及我如何显示消息:



messages.php



以下是我的代码:

 <?php 
/ **************************************** ********** /

// 1.我的textarea表单用于发送消息:
echo< form action ='messages.php?u = $ user'method ='post'enctype ='multipart / form-data'>
< textarea name ='msg_body'rows ='3'maxlength ='255'cols ='110'placeholder ='发送消息...'>< / textarea>
< input type ='submit'name ='send'value ='Send'/>
< input id ='file-名称=附件类型=文件 />
将/形式>中;

/ *
填写上述表格后,以下状态将被视为有效:
1.1。如果textarea不是空的并且没有添加附件。
1.2。如果textarea为空但添加了附件。
1.3。如果textarea和attachment都是空的,那么不要执行INSERT查询。
* /
/ *************************************** *********** /

// 2.我的方法来实现上述和更多...
if($ user!= $ username){
if(isset($ _ POST ['send'])){
$ msg_body =(trim(strip_tags(@ $ _ POST ['msg_body'])));
$ date_of_msg = date(Y-m-d);
$ read =no;
$ deleted =no;

//检查文件是否被添加并且消息被放置
if(($ _FILES ['attachment'] ['size'])== 0&&($ _FILES [ ''附件'] ['error'] == 0)&& $ msg_body!=){
//什么也不做
} else {
if(isset($ _ FILES ('(@ $ _ FILES [attachment] [type] ==image / jpg)
@(@ $ _ FILES [attachment] [type] ==image / jpeg)
||(@ $ _ FILES [attachment] [type] ==image / png)
||(@ $ _ FILES [attachment] [type] ==image / gif))
&&(@ $ _ FILES [attachment] [ size]< 3145728))// 3mb
{
if(file_exists(user_data / attached_files /\".@$_ FILES [attachment] [name])){
// do nothing
} else {
//将临时图像文件移动到一个随机生成的文件中
move_uploaded_file(@ $ _ FILES [attachment] [tmp_name],user_data / attached_files /\".@$_ FILES [attachment]
[name]);
//获取名称
$ attach_name = @ $ _ FILES [attachment] [name];


$ b $ send_msg = mysqli_query($ connect,INSERT INTO private_messages VALUES('','$ username','$ user','$ msg_body' ,
'$ date_of_msg','$ read','$ deleted')
);
} // 396
echo< meta http-equiv ='refresh'content ='0'>;
}
}
/ *********************************** *************** /

// 3.现在显示下载按钮(只有附加了附件时):
$ b $如果($ msg_to == $ user){
echo< div class ='parent'>
< div class ='msg_prof'>
< img class = 'img-rounded'src ='/ user_data / profile_pics / $ my_pro_pic'/>
< / div>
< div class ='new_msg_from_user'>
< p> < b style ='color:red;'>您说过:< / b> $ msg_body< / p>
< span class ='faded'> $ date< / span>;

//检查文件是否为空
if(isset($ _FILES ['attachment'] ['size'])== 0&&(isset($ _ FILES [''附件'] ['error']))== 0){
//没有附加文件,因此不做任何操作
} else {
echo'< form action ='inc / download_attachment .php'method ='post'enctype ='multipart / form-data'>
< button type ='submit'name ='save'>下载< / button>
< /形式>中;
}
echo< a href ='inc / remove_message.php?id = $ message_id'>删除< / a>
< / div>< hr /> ;
< / div>;
}

?>

我的当前结果

所以下面的图片描述了我目前的结果。最后的帖子是空的(你说:)是一个在textarea中没有文本的帖子,但它添加了一个附件。





添加附件时,我需要下载按钮显示如下:

下载按钮一旦按下,将会调用 download_attachment.php 这将强制用户将图像保存到本地磁盘。


摘要


  • 在添加附件时显示下载按钮?

  • 如何防止发送空邮件? (即没有信息和附件)。 对不起,很长的问题:)。

    解决方案

    按顺序回答您的问题:


    如何在添加附件时只显示下载按钮?

    挑战在于,PHP会被服务器端执行并生成一次页面。所以你的逻辑只有在页面刷新(重新生成)时才会起作用。但问题在于你试图实现的是在客户端发生的(点击 Browne ... 按钮)因此我们需要使用JavaScript来解决这个问题。 p>

    因此,我们可以默认隐藏按钮,但在我们与 Browne ... 按钮进行交互时显示它。



    通过在代码的末尾添加以下JavaScript,可以实现这一点

     <脚本> 
    document.getElementById(btnDownload)。style.visibility =hidden;
    document.getElementById(file-input)。onchange = function(){
    document.getElementById(btnDownload)。style.visibility =visible;
    };
    < / script>

    如果您将下载按钮放在的旁边,语句并给它一个id,如 id ='btnDownload'。它也是过度的把它放在PHP里面,所以把它留在HTML中,但是如果你想把它留在PHP里面,不要忘记说把它从任何条件/语句中拿出来,因为我们需要从客户端控制它的外观。

     < form action ='inc / download_attachment.php'method ='post'enctype ='multipart / form-data > 
    < button type ='submit'name ='save'id ='btnDownload'>下载和LT; /按钮>
    < / form>

    这是解决问题的一种方法,换句话说,当图片上传时,您需要在数据库表中添加一个字段以告知文件/附件位置在哪里,如果该字段具有文件/附件位置,则可以通过添加以下条件动态创建下载按钮。

      if(!empty($ attachment))
    {
    //您的按钮生成代码。
    }

    我已经在我的测试环境中用您的代码尝试了两种方法,


    如何防止空邮件被发送? (即没有消息和
    没有附件)。

    你可以用两种方法,你可以添加额外的条件来检查字段是否为空,所以你的代码如下所示:



    < pre $ if($ user!= $ username)
    {
    if(isset($ _ POST ['send'])&&!empty($ _ POST ['msg_body'])){
    代码内.....
    }

    您也可以按照以下


    注意:正如你所看到的,当图像可用于一条消息时,图像按钮出现,我用PHP / MySQL数据库JavaScript和这两个解决方案的工作原理,但因为我没有深入了解你的最终目标,所以我对你的问题的解决方案是工作和概念上正确的,但你可能需要更多的工作和刷它,以适应你的最终目标。



    I am trying to implement a feature which goes something like this:

    1. If textarea has content (not empty) and no attachment is added, then just display the message in the div.
    2. If textarea is empty, but an attachment is added, then display download button, which will force the message receiver to save the attachment to local disk.
    3. If textarea is not empty, and attachment is added, then display both the message and the download button.

    My current situation:

    Currently, I have the following code snippet for processing the attachment (which at the moment, can only be an image). Ideally, I do not want to store anything on the server:

    Firstly, here are is a visual representation of my messages page and how I display my messages:

    messages.php:

    Here is my code:

    <?php
    /**************************************************/
    
    // 1. My textarea form for sending a message:
    echo "  <form action='messages.php?u=$user' method='post' enctype='multipart/form-data'>
                <textarea name='msg_body' rows='3' maxlength='255' cols='110' placeholder='Send message...'></textarea>
                <input type='submit' name='send' value='Send'/>
                <input id='file-input' name='attachment' type='file'/>
            </form>";
    
    /*
    When the above form is filled, the following states are considered valid:
       1.1. If the textarea is not empty and no attachment is added.
       1.2. If the textarea is empty but an attachment is added.
       1.3. If both textarea and attachment are empty, then DO NOT execute the INSERT query.
    */  
    /**************************************************/
    
    // 2. My approach to achieve the above and more...
    if ($user != $username) {
        if (isset($_POST['send'])) {
            $msg_body = (trim(strip_tags(@$_POST['msg_body'])));
            $date_of_msg = date("Y-m-d");
            $read = "no";
            $deleted = "no";
    
            // check if file is added and message is placed
            if (($_FILES['attachment']['size']) == 0 && ($_FILES['attachment']['error'] == 0) && $msg_body != "") {
                // do nothing
            } else {
                if (isset($_FILES['attachment'])) {
                    // check format of file
                    if (((@$_FILES["attachment"]["type"] == "image/jpg") 
                            || (@$_FILES["attachment"]["type"] == "image/jpeg") 
                            || (@$_FILES["attachment"]["type"] == "image/png") 
                            || (@$_FILES["attachment"]["type"] == "image/gif")) 
                            && (@$_FILES["attachment"]["size"] < 3145728)) //3mb 
                    {
                        if (file_exists("user_data/attached_files/".@$_FILES["attachment"]["name"])) {
                            // do nothing
                        } else {
                            // move temporary image files into one of the randomly generated files
                            move_uploaded_file(@$_FILES["attachment"]["tmp_name"], "user_data/attached_files/".@$_FILES["attachment"]
                                ["name"]);
                            // get name         
                            $attach_name = @$_FILES["attachment"]["name"];
                        }
                    }
                }
                $send_msg = mysqli_query($connect, "INSERT INTO private_messages VALUES ('','$username','$user', '$msg_body',
                    '$date_of_msg', '$read', '$deleted')
                ");
            } // 396 
            echo "<meta http-equiv='refresh' content='0'>";     
        }
    }
    /**************************************************/
    
    // 3. Now to display the download button (ONLY IF AN ATTACHMENT IS ADDED):
    
            if ($msg_to == $user){
                echo "  <div class='parent'> 
                            <div class='msg_prof'>
                            <img class='img-rounded' src='/user_data/profile_pics/$my_pro_pic'/>
                        </div>
                        <div class='new_msg_from_user'>
                             <p><b style= 'color: red;'> You said:</b> $msg_body</p>
                             <span class='faded'>$date </span>";
    
                    // check if file is empty
                    if (isset ($_FILES['attachment']['size']) == 0 && (isset($_FILES['attachment']['error'])) == 0){
                        // no file attached, so do nothing
                    } else {
                    echo "  <form action='inc/download_attachment.php' method='post' enctype='multipart/form-data'>
                                <button type='submit' name='save'> Download</button>
                            </form>";
                    }
                    echo "  <a href='inc/remove_message.php?id=$message_id'> Remove </a> 
                        </div><hr/>
                        </div>";
                    }
    
    ?>
    

    My current results:

    So the image below depicts my current results. The last post which is empty (You said: "") was a post with no text in the textarea, but it has an attachment added.

    When an attachment is added, I need the download button to appear like so: The download button, once pressed, will call download_attachment.php which will force the user to save the image to local disk.

    Summary:

    • How do I only show the download button when an attachment is added?
    • How do I prevent empty messages from being sent? (i.e. no message and no attachment).

    P.s. Sorry for the very long question :).

    解决方案

    Answering your question in order:

    How do I only show the download button when an attachment is added?

    The challenge is, PHP get executed and generate the page once by server side. So your logic will only work when page is refreshed (re-generated). But the problem is that what you trying to achieve is happening on Client side (By clicking Browne... button) Therefore we need to use JavaScript to solve this part.

    So we can by default make our button hidden, but display it the moment we interact with Browne... button.

    One way to go, by adding following JavaScript at the end of your code

    <script>
        document.getElementById("btnDownload").style.visibility = "hidden";
        document.getElementById("file-input").onchange = function () {
            document.getElementById("btnDownload").style.visibility = "visible";
        };
    </script>
    

    This will only work if you bring the download button out side of the if statement and give it an id like id='btnDownload'. It is also overkill putting it inside PHP, so just leave it as HTML, but if you want to leave it inside PHP, than remember as said to take it out of the any condition/statement since we need to control its appearance from Client side.

    <form action='inc/download_attachment.php' method='post' enctype='multipart/form-data'>
        <button type='submit' name='save' id='btnDownload'> Download</button>
    </form>
    

    This is one way to solve it, the other way is, when the image get uploaded, you need to added a field in your database table to tell where the file/attachment location is, and if that field has file/attachment location, than you can dynamically create a download button by adding following condition.

    if (!empty($attachment))
    {
        // your button generation code.
    }
    

    I have tried both methods on my test environment with your code and both works.

    How do I prevent empty messages from being sent? (i.e. no message and no attachment).

    You can go two ways, you can added extra condition !empty($_POST['msg_body']) to check if field is not empty, so your code will look like this:

    if ($user != $username)
    {
        if (isset($_POST['send']) && !empty($_POST['msg_body'])){
            code inside etc.....
    }
    

    You can also do it by JavaScript following this example.

    Example of What I did:

    Note: As you can see the image button appears when image available for one messages, I did it both with PHP/MySQL database Or JavaScript and both solutions works, but since I have no in depth knowledge about your final goal, therefore my solution to your question is working and conceptually correct, but you might need to work a bit more and brush it up to fit it in to your final goal.

    这篇关于如果没有附件,则发送消息,否则,刻录下载按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆