upload.vue 2.13 KB
<template>
    <div class="upload">
        <form v-el:form v-on:change="upload">
                <input id="{{inputId}}" type="file" name="filename">
        </form>
    </div>
</template>

<script>
    const modal = require('common/modal');

    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 || '');
                $.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);
                    }
                });
            }
        }
    };
</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>