upload.vue 2.76 KB
<template>
    <div class="upload">
        <form v-el:form @change="upload">
                <input id="{{inputId}}" type="file" name="filename" accept="image/*">
        </form>
    </div>
</template>

<script>
    const yoho = require('yoho');
    const $ = require('jquery');
    const modal = require('common/modal');
    const tip = require('common/tip');

    module.exports = {
        props: ['imageList', 'bucket'],
        data() {
            return {
                inputId: 'input-' + Math.floor(Math.random() * 999999999) // 尽可能保证 input ID 唯一
            };
        },
        methods: {
            upload(e) {
                const formData = new FormData(this.$els.form);

                formData.append('bucket', this.bucket || '');
                yoho.showLoading(true)
                $.ajax({
                    method: 'POST',
                    url: '/api/upload/image',
                    data: formData,
                    processData: false,  // 告诉jQuery不要去处理发送的数据
                    contentType: false   // 告诉jQuery不要去设置Content-Type请求头
                }).then(res => {
                    e.target.value = '';

                    if (res.code === 200) {
                        res.data.imagesList.forEach(imagesPath => {
                            this.imageList.push(imagesPath);
                        });
                    } else {
                        modal.alert(res.message);
                    }
                })
                .fail((jqXhr, textStatus, errorThrow)=> {
                    let message;

                    switch (jqXhr.status) {
                        case 413:
                            message = '图片太大了~';
                            break;
                        default:
                            message = '上传出错~'
                    }

                    tip(message);
                })
                .always(()=>yoho.showLoading(false));
            }
        }
    };
</script>

<style>
    /* 每个地方上传按钮可能不一样,使用的时候自己写样式 */
    .upload {
        position: relative;
        border: 1px solid #b0b0b0;

        &:after, 
        &:before {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100px;
            height: 2px;
            margin-left: -50px;
            margin-top: -1px;
            background-color: #b0b0b0;
        }

        &:before {
            transform: rotate(90deg);
        }

        input {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
        }
    }

</style>