php+ajax文件上传

/**
* css代码
*/
.file-box {
    position: relative;
    display: inline-block;
}
.file-box img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    position: absolute;
    top: -30px;
    left: 0;
    display: inline-block;
    border: none;
}
.file-box .txt,.file-box .file {
    width: 70px;
    height: 36px;
    position: absolute;
    top: -20px;
    left: 100px;
    text-align: center;
}
/**
* HTML5代码
*/
<input type="file" id = "input_file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" "imgPreview(this)">
<img id="preview" />
/**
* JavaScript代码
*/
function imgPreview(fileDom) {
    //判断是否支持FileReader
    if(window.FileReader) {
        var reader = new FileReader();
    } else {
        alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
    }
    //获取文件
    var file = fileDom.files[0];
    var imageType = /^image\//;
    //是否是图片
    if(!imageType.test(file.type)) {
        alert("请选择图片!");
        return;
    }
    //读取完成
    reader.onload = function(e) {
        //获取图片dom
        var img = document.getElementById("preview");
        //图片路径设置为读取的图片
        img.src = e.target.result;
        var formData = new FormData(); 
        formData.append('file', $("#input_file")[0].files[0]);
        $.ajax({
            url:url,
            type: 'POST',
            cache: false, //上传文件不需要缓存
            data: formData,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            success: function (data){
                var user_img = data.path;
                var url = url;
                $.get(url,{u_pic1:user_img},function(msg){
                    if(msg.code == 200)
                    {
                        //alert("路径写入数据库成功");
                    }
                })
            }
        })
    };
	reader.readAsDataURL(file); 
}
/**
* PHP代码
*/
public function uploads()
{
    $file = request()->file('file');
    $info = $file->move( './uploads/');
    $path = '/uploads/'.str_replace('\\', '/', $info->getSaveName());
    if($info){
        return json(['path'=>$path]);
    }else{
        return json(['error'=>$file->getError()]);
    }
}

猜你喜欢

转载自blog.csdn.net/JiaZhaoMeng/article/details/89070024