原生js上传图片至阿里云oss并回显,配合上个帖子的java使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <style>
        .image-container {
            position: relative;
            display: inline-block;
        }

        #avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin-bottom: 20px;
            object-fit: cover;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
            display: block;
        }

        .hover-text {
            position: absolute;
            top: 80%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(228, 228, 228, 0.7);
            color: #8c8b8b;
            padding: 5px 10px;
            border-radius: 5px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 14px;
            width: 60px;
            text-align: center;
        }

        .image-container:hover .hover-text {
            opacity: 1;
        }

        #fileInput {
            display: none;
        }
    </style>
</head>
<body>
<div class="image-container">
    <img id="avatar" src="/icon/个人.png" alt="用户头像">
    <div class="hover-text">修改头像</div>
    <input type="file" id="fileInput" accept="image/*">
</div>

</body>
<script >
    const avatar = document.getElementById('avatar');
    const fileInput = document.getElementById('fileInput');

    avatar.addEventListener('click', () => {
        fileInput.click();
    });

    fileInput.addEventListener('change', () => {
        const file = fileInput.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('image', file);

            const userId = localStorage.getItem('userId');  // 获取用户ID可以不需要,删除即可
            if (userId) {
                formData.append('userId', userId);
            }

            fetch('http://localhost:8080/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        avatar.src = data.data; // 更新头像URL
                        localStorage.setItem('avatar', data.data); // 保存头像URL到 localStorage
                    } else {
                        alert('上传失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('上传出错');
                });
        }
    });

</script>
</html>
  • 18
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值