【问题标题】:How to send mail with multiple file attachements如何发送带有多个文件附件的邮件
【发布时间】:2021-02-19 11:00:07
【问题描述】:

我的 Vue.js 应用程序上有一个 ContactForm,用于向我的 Go 后端发送电子邮件,除了文件上传之外,一切似乎都工作正常。

这是将文件推送到表单的函数。

onFileChanged (e) {
  this.files = new FormData()
  for (let i in e.target.files) {
    if (e.target.files[i].type) {
      let file = e.target.files[i]
      this.form.files.push(file)
    }
  }
},

这是将数据发送到我的后端的函数

async sendMail () {
          try {
            await axios.post(process.env.API_URL + '/api/email',this.form, this.to)
            this.$awn.success(this.$t('message_sent'))
            this.error = false
            this.processed = false
            this.response = true
          } catch (e) {
            this.$awn.alert(e.response.data.message)
            this.error = true
            this.processed = false
          }
},

如果我发送不带文件附件的表单,一切正常。

当我附加一个或多个文件并 console.log 表单时,文件作为数组存在于表单数据中,但请求中的 files 数组为空。

我使用 axios 发送到 API 的表单的控制台日志。

请求负载:

{"busy":false,"successful":false,"errors":{"errors":{}},"originalData":{"subject":null,"to":null,"email":null,"message":null,"files":[],"allowedmedia":"gif,png,jpg,jpeg,ogg,mp3,flac,avi,mpg,mpeg,mkv,webm,pdf,txt,odt,ott,ods,ots,odp,otp,odg,otg","human":"test"},"subject":"test","to":"admin@domain.tld","email":"test@test.com","message":"test","files":[{},{}],"allowedmedia":"gif,png,jpg,jpeg,ogg,mp3,flac,avi,mpg,mpeg,mkv,webm,pdf,txt,odt,ott,ods,ots,odp,otp,odg,otg","human":""}

如您所见,请求中的 files 数组包含两个空对象 [{},{}]。

我不明白我在这里做错了什么,所以任何帮助将不胜感激,谢谢。 如果您需要查看后端的 GO 代码,请告诉我,但我很确定我在前端做错了什么。

【问题讨论】:

    标签: javascript vue.js go axios gomail


    【解决方案1】:

    您使用 append 方法将内容添加到 FormData。

    所以你的代码应该是这样的:

    onFileChanged (e) {
      this.form = new FormData(); // maybe it's better to initialize your form outside of this function
      for (const file of e.target.files) {
        if (file.type) {
          this.form.append('files[]', file)
        }
      }
    },
    

    另见answer

    【讨论】:

    • 感谢您的回答,我试过了,但现在当我 console.log 表单时文件甚至都不存在。
    • 可能与变量不一致。我将 this.form.files 更改为 this.files。我在回答中更正了这一点。
    猜你喜欢
    • 2020-01-04
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多