【问题标题】:How do I convert my uploaded file to json如何将我上传的文件转换为 json
【发布时间】:2021-12-16 00:05:19
【问题描述】:

我正在编写一个使用 vuejs 作为前端和 laravel 8 作为后端的应用程序

我想让用户从他们的本地计算机中选择一张图片并将其发送到后端。

我想先把它转换成json,然后再发送到服务器

但是当我将其转换为 json 时,json 对象变为空

模板

<input type="file" @change="uploadFile( $event, index, idx )" name="" id="">

Vuejs

export default {
  name: 'CreateCourse',
  setup(){
    const file = reactive({"file" :''})
    const uploadFile = (e, idx, i) => {
            file.file = e.target.files[0];
            console.log("no json", file.file);
            console.log("Object file is ",JSON.parse(JSON.stringify(file.file)));
        }

    const formData = new FormData();
    formData.append("file", file);


    axios.post('http://127.0.0.1:8000/api/v1/courses', formData, {
        headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en;q=0.8',
        'Content-Type': 'multipart/form-data'
        }
    }).then(response => {
       
    }).catch(err => {
        NotificationService.error(err.response);
        showLoader(false);
    });
return {
        uploadFile
    }
   }
}

没有 json 的 console.log 显示上传的文件,但带有 object 文件的 console.log 显示空的 json 对象。我该怎么办?

【问题讨论】:

    标签: arrays json laravel vue.js form-data


    【解决方案1】:

    该文件为缓冲区格式,需要转换为字符串,因此JSON.parse 将不起作用。 阅读更多here

    【讨论】:

    • 我还删除了 JSON.parse 并使用了 JSON.stringify 但它对我不起作用
    • 在尝试 JSON.parse 之前将缓冲区转换为字符串
    猜你喜欢
    • 2022-06-13
    • 2023-01-17
    • 1970-01-01
    • 2022-10-16
    • 2014-10-26
    • 2022-01-07
    • 1970-01-01
    • 2014-11-11
    • 2019-02-23
    相关资源
    最近更新 更多