Vue中接口发送file文件给后端

1:先取到要传递的File文件

this.filecontent = file;

2:通过FormData添加数据

 var formData=new FormData(form);
 // 通过append()方法追加数据
 formData.append("data","fileContent");

3:最后通过接口发送

this.$http
        .post(that.$api.xxxx, data, {
          headers: { "Content-Type": "multipart/form-data" },
          transformRequest: [
            function(d) {
              return d;
            }
          ]
        })
        .then(res => {
          if (res.data.code == 200) {
           
          }
        });

 

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你可以使用 `el-upload` 组件来上传文件,然后在上传成功的回调函数获取到文件对象,并将其传递后端。 以下是一个基本的示例: ```vue <template> <el-upload action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" > <el-button>上传文件</el-button> </el-upload> </template> <script> export default { methods: { handleSuccess(response, file) { console.log('上传成功', response, file) }, beforeUpload(file) { // 如果需要限制上传的文件类型,可以在这里进行判断 console.log('准备上传', file) } } } </script> ``` 在以上示例,`action` 属性指定了上传文件接口地址,`on-success` 属性指定了上传成功后的回调函数,`before-upload` 属性指定了上传前的回调函数。你需要根据自己的需求修改这些属性的值。 在 `handleSuccess` 回调函数,你可以获取到后端返回的数据和上传的文件对象。你可以将文件对象传递后端,例如使用 `axios` 发送 POST 请求: ```js import axios from 'axios' handleSuccess(response, file) { console.log('上传成功', response, file) const formData = new FormData() formData.append('file', file) axios.post('/api/upload-file', formData) .then(res => { console.log('后端返回数据', res.data) }) } ``` 在以上代码,我们将文件对象添加到 `FormData` 对象,并使用 `axios` 发送 POST 请求,将该 `FormData` 对象作为参数传递后端接口 `/api/upload-file`。你需要根据自己的接口地址和请求方式进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

让我看看谁在学习

你的鼓励是我创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值