使用Ajax MySQL PHP上传图片

3

我希望尝试使用PHP和MySQL上传图片。我正在使用一个表单来使用ajax发送数据。

我的HTML代码:

<input type="file" name="logo" id="logo" class="styled">
<textarea rows="5" cols="5" name="desc" id="desc" class="form-control"></textarea>
<input type="submit" value="Add" id="btnSubmit" class="btn btn-primary">

Ajax 代码:

var formData = new FormData($("#frm_data")[0]);
$("#btnSubmit").attr('value', 'Please Wait...');
$.ajax({
    url: 'submit_job.php',  
    data: formData,
    cache: false,
    contentType:false,
    processData:false,
    type: 'post',
    success: function(response)

我的php代码(submit_job.php):

$desc =  mysqli_real_escape_string($con, $_POST['desc']);
$date = date('Y-m-d H:i:s');
$target_dir = "jobimg/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file);
3个回答

6
请试试这个:
Jquery:
$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();  // Create a FormData object
        form_data.append('file', file_data);  // Append all element in FormData  object

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the input type file */
    });

Php:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>

move_uploaded_file(jobimg/banner-_pipe-_puzzle.png): failed to open stream: No such file or directory in C:\wamp\www\jobPortalplus\Admin\submit_job.php on line 37 - Meena patel
但我也想将图像名称存储在数据库中。我该如何将图像名称存储在变量中? - Meena patel
你可以在 If 语句中实现这个功能,通过在数据库上执行插入查询来放置消息 “文件上传成功” - Mayank Pandeyz
如何将图像名称存入变量中? - Meena patel
$_FILES['file']['name']: - Mayank Pandeyz
显示剩余4条评论

2
安全是网页设计的重要部分。尝试使用以下验证来增加安全性。
检查$_FILES中的文件。
if (empty($_FILES['image']))
    throw new Exception('Image file is missing');

检查上传时间错误
if ($image['error'] !== 0) {
    if ($image['error'] === 1) 
        throw new Exception('Max upload size exceeded');

    throw new Exception('Image uploading error: INI Error');
}

检查上传的文件。
if (!file_exists($image['tmp_name']))
    throw new Exception('Image file is missing in the server');

检查文件大小
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
    throw new Exception('Max size limit exceeded'); 

验证图像。
$imageData = getimagesize($image['tmp_name']);
if (!$imageData) 
    throw new Exception('Invalid image');

验证Mime类型
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes)) 
    throw new Exception('Only JPEG, PNG and GIFs are allowed');

希望这能帮助其他人创建一个没有安全问题的上传PHP脚本。

源代码


1
<script type="text/javascript">
    $(document).ready(function () {
        $("form").submit(function (event) {
           event.preventDefault();
            var formdata = new FormData($('form')[0]);
            var url = $("form").attr('action');
            $.ajax({
                url: url,
                type: "POST",
                data: formdata,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log(data);
                }
            });
        });
    });
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接