duanjiaonie6097 2017-01-20 09:51
浏览 117
已采纳

使用ajax mysql php上传图片

I want to try uploading an image using php and mysql. I'm using a form to send data using ajax.

My Html Code:

<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 Code:

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)

my php code (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条回答 默认 最新

  • doutuoji8418 2017-01-20 09:53
    关注

    Try this:

    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 file container */
        });
    

    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";
            }
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 Js代码报错问题不知道怎么解决
  • ¥15 gojs 点击按钮node的position位置进行改变,再次点击回到原来的位置
  • ¥15 计算决策面并仿真附上结果
  • ¥20 halcon 图像拼接
  • ¥15 webstorm上开发的vue3+vite5+typeScript打包时报错
  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥100 求ASMedia ASM1184e & ASM1187e 芯片datasheet/规格书
  • ¥15 求解决扩散模型代码问题