单个文件上传jquery php

时间:2016-09-16 13:27:55

标签: php jquery upload

我确定我在这个问题上犯了一个简单的错误。该文件未传递到php页面(我收到“未上传:文件错误。请再试一次。”错误从PHP页面传回。)

代码在没有JQUERY的情况下工作正常,所以我猜PHP不是问题。

我检查了字段名称/ ID&好像没问题。我试着测试看按钮的值是否正在传递但事实并非如此,那时我得出结论可能是JQUERY,但后来我感到难过。

我知道已经提交了类似的帖子(我已经阅读过了)但是我很绝望!!

提前谢谢。

这是HTML:

    <form action="upload.php" name="formname" ENCTYPE="multipart/form-data" id="formid">
        <fieldset>
            <legend>File info</legend>
            <p>
                <label for="file1">Files<span class="red"> *</span></label>
                <input name="file1" type="file" />
            </p>
        </fieldset>
        <p><label>&nbsp;</label><input type="button" id="submit" value="Add" /></p>
    </form>
    <div id="output"></div>

<script>
$(function(){
    $('#submit').on('click', function(){ 
        var fd = new FormData($("#formid"));
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});
</script>

和PHP

<?php
    $strName = 'JoeBloggs';
    $intId = 1045;
    $missing = '';
    date_default_timezone_set("Europe/London");
    error_reporting(E_ALL);
    include('class.upload.php');
    // where to put the images?
    $dir_dest = '../'.$intId.'/';
    $xcount = 0;
    if (!file_exists($dir_dest)) { mkdir($dir_dest, 0777, true);}
    # upload 1400px
    $handle = new upload($_FILES['file1']);
    if ($handle->uploaded) {
        $y = $handle->image_src_y;
        $height = $y/2;
        $handle->image_resize           = true;
        $handle->image_ratio_crop       = true;
        $handle->image_x                = 700;
        $handle->image_y                = 260;
        $handle->image_convert          = jpg;
        $handle->Process($dir_dest);
        if ($handle->processed) {
            // everything was fine !
            $strFilename1 = $handle->file_dst_name;
            rename( $dir_dest . $strFilename1, $dir_dest . $strName . '.jpg' );
            $missing .= 'File uploaded';
        } else {
            $missing .= $missing. 'Not processed:' . $handle->error . '<br />';
        }
    } else {
        $missing .= 'Not uploaded:' . $handle->error . '<br />';
    }

    echo $missing;
    //header('Location: ../index.php?missing='.$missing);
?>
<img src="<?= $dir_dest . $strName?>.jpg" />

2 个答案:

答案 0 :(得分:1)

试试这可能会对你有帮助,

<script>
 $(function(){
  $('#submit').on('click', function(){ 
    var form = $('#formid')[0];
    var formData = new FormData(form);
    $.ajax({
        url: 'upload.php',  
        type: 'POST',
        data: formData,
        success:function(data){
            $('#output').html(data);
        },
        cache: false,
        contentType: false,
        processData: false
    });
});
});
</script>

答案 1 :(得分:0)

尝试添加到ajax函数:

contentType: multipart/form-data