上传文件的两种方式

 由于我的页面有多个上传文件的input所以需要传一个index进去区分,如果只有一个上传可以将index去掉

//上传图片
function upLoad1(index){
    var formData = new FormData();
    var img_file = document.getElementById("upimg"+index);
    var fileObj = img_file.files[0];
    console.log(fileObj.size)
    var size=fileObj.size/1024;
    if(size>2000){
        toast('图片不能超过2M')
        fileObj=""
        return
    }else{
        formData.append("file",fileObj);
        formData.append("path","store");
        $.ajax({
            url:"http://shop.superstar520.com/api/v1/common/uploadImg",
            type:"post",
            data:formData,
            async:false,
            processData : false,
            contentType : false,
            success:function(data){ 
                  if(data.code==200){
                    $("#img"+index).attr('src',data.data.url);
                  }else{
                    toast(data.data.message)
                  }
            }
        });
    } 
}
// 第二种上传方法
function upLoad(index){
    var fileInput = document.getElementById("upimg"+index);
    var file = fileInput.files[0];
    console.log(file.name)
    //创建读取文件的对象
    var reader = new FileReader();         
    //创建文件读取相关的变量
    var imgFile;         
    //为文件读取成功设置事件
    reader.onload=function(e) {
        // alert('文件读取完成');
        console.log(e)
        imgFile = e.target.result;
        // console.log(imgFile);
        $("#img"+index).attr('src',imgFile);
        $.ajax({
            url:"http://shop.superstar520.com/api/v1/common/uploadImg",
            type:"post",
            headers: {
                'Content-Type':'application/x-www-form-urlencoded'
            },
            data:{
                "file":file.name,
                "path":'store'
            },
            success:function(data){
                  console.log(data)
            }
        });
    };

    //正式读取文件
    reader.readAsDataURL(file);
}

 注:toast 是封装的一个弱提示

猜你喜欢

转载自www.cnblogs.com/ldlx-mars/p/10619116.html