使用 VueJS AJAX 和 Laravel 5.3 上传多个文件

web*_*Dev 2 php api file-upload vue.js laravel-5.3

我使用VueJSLaravel 5.3编写单页应用程序

我已经使用 Laravel 5.3 开发了我的后端 API 端点,但我不擅长前端开发,例如 vueJS。我正在尝试使用 VueJS 和 Laravel 5.3 上传多个文件。

sha*_*any 5

这可能比您需要的晚,但它仍然可能帮助那些正在寻找它的人。

首先,使用 axios 库将文件从前端发送到后端。

确保在 Javascript 端使用 FormData。

这是一段代码,可帮助您处理上传并将其发送到服务器。

< input type = "file"
multiple = "multiple"
id = "attachments"
@change = "uploadFieldChange" >

    // This function will be called every time you add a file
    uploadFieldChange(e) {

        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
            return;

        for (var i = files.length - 1; i >= 0; i--) {
            this.attachments.push(files[i]);
        }

        // Reset the form to avoid copying these files multiple times into this.attachments
        document.getElementById("attachments").value = [];
    }

submit() {

    this.prepareFields();

    var config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: function (progressEvent) {
            this.percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            this.$forceUpdate();
        }.bind(this)
    };

    // Make HTTP request to store announcement
    axios.post(this.settings.file_management.upload_files, this.data, config)
        .then(function (response) {
            console.log(response);
            if (response.data.success) {
                console.log('Successfull Upload');
                toastr.success('Files Uploaded!', 'Success');
                this.resetData();
            } else {
                console.log('Unsuccessful Upload');
                this.errors = response.data.errors;
            }
        }.bind(this)) // Make sure we bind Vue Component object to this funtion so we get a handle of it in order to call its other methods
        .catch(function (error) {
            console.log(error);
        });

}
Run Code Online (Sandbox Code Playgroud)

完整的解决方案有更多的代码行,并包含在 Laravel 项目中。

您可以在 Medium 上找到更多详细信息:https : //medium.com/@adnanxteam/how-to-upload-multiple-files-via-ajax-vuejs-and-laravel-5-5-file-management-d218c3bbb71c