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

<script>
    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 {
                        alert(res.message);
                    }
                });
            }
        }
    };
</script>

<style>
    /* 每个地方上传按钮可能不一样,使用的时候自己写样式 */
</style>