使用FormData对象使用$.(ajax)传文件,使用filereader预览

<我是菜鸟——简单快捷无原理>

要是你不小心看到我的,有更更更好的理解和方法,一定要告诉我。

①<input>file标签属性的隐藏

    因为input上传的时候,标签后面会跟路径,这个样式是很丑的,然而无法改变样式,

    所以使用<label for=“<input>的id”>来设置样式。

 

②在使用append()方法的时候,我想知道到底有没有追加进去,就用console.log()输出对象为空,纠结了好久,然后很蠢的知道了:

因为外界访问不到。你使用append方法后,对应的键值对就已经添加到表单里面了,你在控制台看到的是FormData原型,存储的数据没有以对象属性的方式体现。

action接收jsp传来的值,主要的方式是将数据放在request对象中,然后在另一个页面拿到这个数据。application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。

你可以通过formData.get("qweqwe")的方式获取到对应的表单数据。

 

ajax的异步 和filereader的异步onload()

我是这样理解的:

解释一:

有A(主要非异步文档流)、B(执行任务success()和onload()方法体)两个车间流水线,

A的主管叫一个小助手k(success()和onload())去B给A传个信息过来,(A要继续,不能被影响,不等待信息,交给B间)

那么k去B之间需要时间(此时已经离开A,A不知道k什么时候回来),

在k接到指令(执行路过)去B的过程,A得不到信息,

解释二:

异步调用就是你 喊 你朋友吃饭 ,你朋友说知道了 ,待会忙完去找你 ,你就去做别的了,最后一起吃饭。

同步调用就是你 喊 你朋友吃饭 ,你朋友在忙 ,你就一直在那等,等你朋友忙完了 ,你们一起去。

所以在success()(onload())中赋值给变量,立马在success外取值是得不到(此时可能这个),需要等待几毫秒(但是程序执行很快,毫秒足够报错)

如程序中我的延迟测试,就可以取到我在onload()里面得到的imgCode的值。

以上的时间,是非常短非常短的毫秒。

"异步模式":每一个任务有一个或多个回调函数(callback),前一个任务结束后,不是执行后一个任务,而是执行回调函数,后一个任务则是不等前一个任务结束就执行,所以程序的执行顺序与任务的排列顺序是不一致的、异步。

 "异步模式"非常重要。在浏览器端,耗时很长的操作都应该异步执行,避免浏览器失去响应,最好的例子就是Ajax操作。

 

代码如下:

 

HTML:

 

<form>
    <div class="upload-md">
        <div class="up-wj">

            <abbr>上传文件</abbr>

            <div class="input clr" >
                <img src="img/icon_file.png" alt="" >
                <input type="text" placeholder=" 未选择文件" id="em">
                <input type="file" id="file" ><label for="file" class="btn">选择文件</label>
            </div>

        </div>
        <div class="up-al">
         <span>
              <img src="img/icon_upload.png" alt="">
                上&nbsp;&nbsp;&nbsp;传
         </span>
        </div>
    </div>
</form>

JavaScript:

②fileM获取input的对象

③绑定input的事件,addEventListener()方法,input里面值改变时触发,得到文件对象files。

 

var oMyForm = new FormData();

 

 
var fileM = document.getElementById("file");
var fileM = document.getElementById("file");
    fileM.addEventListener('change',function (e) {
    document.getElementById("em").value = document.getElementById("file").value;
    var files=e.target.files;
    console.log(files);
    for(var i=0;i<files.length;i++){
        var fileSize=files[i].size;
        var size=fileSize/1024;

        if(size>50000){
            return alert("附件不可大于50M");
        }
        file_name = files[i].name;
        oMyForm.append('file',files[i]);
        oMyForm.append('company_id',company_id);
        oMyForm.append('project_id',project_id);
        oMyForm.append('file_class_id',file_class_id);
        oMyForm.append('file_name',file_name);
        console.log(oMyForm);
    }
})
function uploadFile() {
    $.ajax({
        url: "http://bike.wei-yong.com/gct/index/file_upload",
        type: 'post',
        dataType: "json",
        processData:false,   //  告诉jquery不要处理发送的数据
        contentType:false,    // 告诉jquery不要设置content-Type请求头
        cache:false,
        data: oMyForm,
        success: function (data) {
            console.log(data);
           if(data.status==1){
               $(".zt-1").hide();
               $(".up-true").show().find(".zt-qd").on("click", function () {
                   // $(location).attr("href","MProject.html");
                   $('.statepage').hide();
                   $('.statepage').eq(0).show();
                   // $('.statepage').toggle();
                   $(".upload-md input").val("");

               });
           }else{
               alert("错误提示:"+data.info);
           }
        },
        error: function (err) {
            alert("错误:"+err.statusText);
        }
    })
}

CSS

.upload-md{
    margin-top: 240px;
    position: relative;
    left: -63px;
}
.upload-md>div {
    margin: 20px auto;
}
.upload-md input {
    width: 626px;
    height: 64px;
    border: none;
    background: #E9EFF6;
    border-radius: 8px;
    font-size: 28px;
}
.up-wj {
    font-family: PingFangSC-Regular;
    font-size: 28px;
    color: #89A1BE;
    letter-spacing: 0;
    text-align: center;
    padding-left: 18px;
}
.up-wj img {
    position: relative;
    left: 13px;
}
img {
    vertical-align: middle;
}
.upload-md .input input:nth-of-type(1){
    width: 364px;
    height: 64px;
    border: none;
    background: #E9EFF6;
    border-radius: 8px;
    font-size: 28px;
    margin-left: 11px;
    outline: none;
    overflow: hidden;  /*溢出隐藏*/
    text-overflow: ellipsis; /*以省略号...显示*/
    white-space: nowrap;  /*强制不换行*/
}
.input{
    display: inline-block;
    width: 626px;
    height: 64px;
    border: none;
    background: #E9EFF6;
    border-radius: 8px;
    position: relative;
    left: 4px;
}
.up-wj #file{
    display: none;
}
.up-wj abbr{
    position: relative;
}
.btn{
    float: right;
    display: inline-block;
    width: 190px;
    height: 64px;
    line-height: 64px;
    text-align: center;
    background: #C9D6E9;
    color: #405C8A;
    border-radius: 8px;
    /*position: relative;*/
    left: -200px;
    top: 4px;
}

后追加上传图片和预览

JavaScript:

 

var image;
var file;
// 创建一个空的BIMForm对象
var BIMForm = new FormData();
var ImgFile = document.getElementById("maip");

 

ImgFile.addEventListener('change', function (e) {
    var reader = new FileReader();
    var imgCode;
    //image对象
    console.log("上传图片");
    image = $("#maip")[0].files[0];
    reader.readAsDataURL(image);
    console.log(image);
    reader.onload = function (e) {
        imgCode = e.target.result;
        $("#upimg").attr('src', imgCode);
    }
       BIMForm.append('image', image)
    //延迟时间测试
    setTimeout(function () {
        console.log(imgCode + "!!!!")
    }, 10)
})

filereader使用(反正网上一大票,我就贴个地址)

点击打开链接

点击打开链接

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值