上传头像源码(JS)

文件上传

formData文件上传:

//源码
<input type="file">


//支持文件上传,用post方式提交formData对象,键为文件名,值为文件
eg:
var ele = document.querySelector('input');
ele.onchange = function(e){
    console.log('e...', e);
    let files = e.target.files;
    // 创建一个formData
    let form = new FormData();
    for (let i=0,len=files.length; i<len;i++){
        console.log(files[i].name);
        form.append(files[i].name, files[i]);
    }

    axios({
        method: 'post',
        url: 'http://123.206.55.50:11000/upload',
        data: form
    }).then(body=>{
        console.log('body...', body);
    }).catch(e=>{
        console.log('e..', e);
    })
    
     // jquery版本
    let input = document.querySelector('input');
    input.onchange = function(e){
        console.log('e..', e.target.files);
        let form = new FormData();
        for (let i=0,len=e.target.files.length; i<len; i++){
            form.append(e.target.files[i].name, e.target.files[i]);
        }

        $.ajax({
            method: 'post',
            url: 'http://123.206.55.50:11000/upload',
            processData: false,
            contentType: false,
            data: form,
            dataType:"json",
            success: function(res){
                console.log('res...', res)
            }
        })
    }
}

**base64图片上传 **

//源码
<input type="file">



var ele = document.querySelector('input');
ele.onchange = function(e){
    let files = e.target.files;
    var reader = new FileReader();
    reader.onload = function(){
        console.log('result...', this.result);
        axios({
            method: 'post',
            url: 'http://123.206.55.50:11000/upload_base64',
            data: {base64: this.result}
        }).then(body=>{
            console.log('body...', body);
        }).catch(e=>{
            console.log('e..', e);
        })
    }
    reader.readAsDataURL(files[0]);
}

**图片转成base64 **

//源码
axios({
    method: 'post',
    url: 'http://123.206.55.50:11000/tobase64',
    data: {url: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3360034032,4096528553&fm=26&gp=0.jpg'}
}).then(body=>{
    console.log('body...', body);
}).catch(e=>{
    console.log('e..', e);
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值