最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Inserting file name to the database - Stack Overflow

programmeradmin5浏览0评论

I am using a photo upload script which can be found at

This is the HTML:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
      <textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
      <div class="media"><input type="file" name="files[]" id="filer_input2" multiple="multiple"></div>
      <input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>

This is the Jquery which sends data to post-status.php:

//Get Image Value and Assign it to class mediafile
$('#filer_input2').change(function(){
    var files = $(this)[0].files;
    var output = "";
    for(var i = 0; i < files.length; i++){
        console.log(files[i].name);
        output += files[i].name+";";
    }
    var media = $(".mediafile").val(output);
});

// STATUS UPDATE
$(function() {
    $("#submit").click(function() {
        var textcontent = $(".newstatuscontent").val();
        if(media == ''){
            if(textcontent == ''){
                $('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
            }
        }else{
            $.ajax({
                type: "POST",
                url: "post-status.php",
                data: {content:textcontent},
                cache: true,
                success: function(html){
                    $("#shownewstatus").after(html);
                    $(".newstatuscontent").val('');
                }  
            });
        }
        return false;
    });
});

This is the PHP file which renames the files (images) and uploads them to the uploads folder.

<?php
    include('class.uploader.php');

    $uploader = new Uploader();
    $data = $uploader->upload($_FILES['files'], array(
        'limit' => 10, //Maximum Limit of files. {null, Number}
        'maxSize' => 10, //Maximum Size of files {null, Number(in MB's)}
        'extensions' => null, //Whitelist for file extension. {null, Array(ex: array('jpg', 'png'))}
        'required' => false, //Minimum one file is required for upload {Boolean}
        'uploadDir' => '../uploads/', //Upload directory {String}
        'title' =>  array('{{random}}{{.extension}}', 32), //New file name {null, String, Array} *please read documentation in README.md
        'removeFiles' => true, //Enable file exclusion {Boolean(extra for jQuery.filer), String($_POST field name containing json data with file names)}
        'replace' => false, //Replace the file if it already exists  {Boolean}
        'perms' => null, //Uploaded file permisions {null, Number}
        'onCheck' => null, //A callback function name to be called by checking a file for errors (must return an array) | ($file) | Callback
        'onError' => null, //A callback function name to be called if an error occured (must return an array) | ($errors, $file) | Callback
        'onSuccess' => null, //A callback function name to be called if all files were successfully uploaded | ($files, $metas) | Callback
        'onUpload' => null, //A callback function name to be called if all files were successfully uploaded (must return an array) | ($file) | Callback
        'onComplete' => null, //A callback function name to be called when upload is plete | ($file) | Callback
        'onRemove' => null //A callback function name to be called by removing files (must return an array) | ($removed_files) | Callback
    ));

    if($data['isComplete']){
        $files = $data['data'];

        echo json_encode($files['metas'][0]['name']);
    }

    if($data['hasErrors']){
        $errors = $data['errors'];
        echo json_encode($errors);
    }

    exit;
?>

Now the problem:

You can see there is a textarea and file input in the form. I want to insert the textarea data and names of the images uploaded to the database. But the image is being renamed and uploaded with the PHP script given above. And the status is posted by a custom php script written by me in post-status.php. What I want is I want the renamed file name to be sent to the post-status.php page so that I can insert it into the database. But since this is an external script that I am using for uplaoding photos I am not being able to bine it with my script. Please help me guys. You can download the script from the above given link.

I am using a photo upload script which can be found at https://github./CreativeDream/php-uploader

This is the HTML:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
      <textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
      <div class="media"><input type="file" name="files[]" id="filer_input2" multiple="multiple"></div>
      <input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>

This is the Jquery which sends data to post-status.php:

//Get Image Value and Assign it to class mediafile
$('#filer_input2').change(function(){
    var files = $(this)[0].files;
    var output = "";
    for(var i = 0; i < files.length; i++){
        console.log(files[i].name);
        output += files[i].name+";";
    }
    var media = $(".mediafile").val(output);
});

// STATUS UPDATE
$(function() {
    $("#submit").click(function() {
        var textcontent = $(".newstatuscontent").val();
        if(media == ''){
            if(textcontent == ''){
                $('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
            }
        }else{
            $.ajax({
                type: "POST",
                url: "post-status.php",
                data: {content:textcontent},
                cache: true,
                success: function(html){
                    $("#shownewstatus").after(html);
                    $(".newstatuscontent").val('');
                }  
            });
        }
        return false;
    });
});

This is the PHP file which renames the files (images) and uploads them to the uploads folder.

<?php
    include('class.uploader.php');

    $uploader = new Uploader();
    $data = $uploader->upload($_FILES['files'], array(
        'limit' => 10, //Maximum Limit of files. {null, Number}
        'maxSize' => 10, //Maximum Size of files {null, Number(in MB's)}
        'extensions' => null, //Whitelist for file extension. {null, Array(ex: array('jpg', 'png'))}
        'required' => false, //Minimum one file is required for upload {Boolean}
        'uploadDir' => '../uploads/', //Upload directory {String}
        'title' =>  array('{{random}}{{.extension}}', 32), //New file name {null, String, Array} *please read documentation in README.md
        'removeFiles' => true, //Enable file exclusion {Boolean(extra for jQuery.filer), String($_POST field name containing json data with file names)}
        'replace' => false, //Replace the file if it already exists  {Boolean}
        'perms' => null, //Uploaded file permisions {null, Number}
        'onCheck' => null, //A callback function name to be called by checking a file for errors (must return an array) | ($file) | Callback
        'onError' => null, //A callback function name to be called if an error occured (must return an array) | ($errors, $file) | Callback
        'onSuccess' => null, //A callback function name to be called if all files were successfully uploaded | ($files, $metas) | Callback
        'onUpload' => null, //A callback function name to be called if all files were successfully uploaded (must return an array) | ($file) | Callback
        'onComplete' => null, //A callback function name to be called when upload is plete | ($file) | Callback
        'onRemove' => null //A callback function name to be called by removing files (must return an array) | ($removed_files) | Callback
    ));

    if($data['isComplete']){
        $files = $data['data'];

        echo json_encode($files['metas'][0]['name']);
    }

    if($data['hasErrors']){
        $errors = $data['errors'];
        echo json_encode($errors);
    }

    exit;
?>

Now the problem:

You can see there is a textarea and file input in the form. I want to insert the textarea data and names of the images uploaded to the database. But the image is being renamed and uploaded with the PHP script given above. And the status is posted by a custom php script written by me in post-status.php. What I want is I want the renamed file name to be sent to the post-status.php page so that I can insert it into the database. But since this is an external script that I am using for uplaoding photos I am not being able to bine it with my script. Please help me guys. You can download the script from the above given link.

Share Improve this question edited Nov 13, 2016 at 5:37 hisener 1,5011 gold badge17 silver badges26 bronze badges asked Nov 9, 2016 at 11:48 user6224087user6224087 5
  • I think your code is not pleted, you might consider few issues to fix before fixing the real problem, first you need to add multipart/form-data as answered below, also this line "if(media == '')" this is not jQuery ... work on your code and make it upload files successfully, then consider solving the names issue. – Doaa Magdy Commented Nov 14, 2016 at 9:25
  • What output are you getting so far? Question of working with file and textarea es after you know what are the posted contents? Did you try to debug them? – Rahi Commented Nov 14, 2016 at 16:40
  • everything You do is totally wrong. You should do 1 request with uploading and data sending from inputs. Use "jquery form" plugin, it wraps Your form with ajax stuff without additional coding, just needed redevelop serverside part. – num8er Commented Nov 15, 2016 at 9:49
  • You can get answer from : stackoverflow./questions/2320069/jquery-ajax-file-upload – Vikas Kumar Commented Nov 16, 2016 at 12:42
  • you want to rename means what? if you have upload file "123.jpg" then in DB "123.jpg" should be save or something else of your choice name? – Archish Commented Nov 19, 2016 at 6:39
Add a ment  | 

2 Answers 2

Reset to default 6 +25

First of all there are some issues with the form in your HTML-code, as mentioned by some people already. One of the issues is that you need to use the multipart-form-data enctype in order to be able to upload a file. If not, then the $_FILES array will be empty and nothing uploaded.
Another thing the runat="server" attribute in the form tag. This is pletely unnecessary, and only used in ASP.
The third, and most ctritical one, is that $_SERVER['PHP_SELF'] is vulnerable for XSS attacks!

Then, to your question. If you'd checked out the source code of the class you're using, you'd see that the onComplete function is called after a file has been uploaded successfully. With the $metas array as its second argument. This array contains the new filename, under the index name.
Or, you can use the onSuccess method, to insert the filenames as the files are uploaded.

Maybe you should use "enctype= multipart/form-data" properties in <form> tag

<form method="post" enctype= multipart/form-data action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server">
发布评论

评论列表(0)

  1. 暂无评论