繁体   English   中英

无法使用 Vue.js 和 Axios 上传文件

[英]Unable to upload file with Vue.js and Axios

我想使用 axios 和 vue.js 将文件上传到 Java 后端。 我知道后端运行良好,因为如果我使用这个 curl 命令,我可以毫无问题地到达它。

curl --location --request POST 'http://localhost:8081/steg/aaa' --form 'file=@"/home/mycomputer/Files/image.png"' -o result.png

但是当尝试从应用程序 GUI 执行相同操作时,我不断收到 400 错误:

在此处输入图像描述

我不知道为什么会这样。 在这里,我添加了这个组件的代码,以查看它是否与 curl 命令的行为相匹配:

<template>
  <div class="steg">
    <input type="file" @change="onFileSelected">
    <input type="text" v-model="secretText" placeholder="edit me">
    <button @click="onUpload"> Steg</button>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Steg",
  data() {
    return {
      selectedFile: null,
      secretText: null
    }
  },
  methods: {
    onFileSelected(event) {
      this.selectedFile = event.target.files[0]
    },
    onUpload() {
      const formData = new FormData()
      formData.append('image', this.selectedFile, this.selectedFile.name)
      axios.post('http://localhost:8081/steg/' + this.secretText, formData)
          .then(response => {
            console.log(response.status)
          })
    }
  }
}
</script>

<style scoped>

</style>

所以我不确定它可能是什么。 curl 命令有效,但 vue 应用程序无效。 以防万一我要在这里上传 Java 后端代码,但我认为那里一切正常。

    @CrossOrigin
    @RequestMapping(value = STEG_ENDPOINT, method = POST, produces = APPLICATION_OCTET_STREAM_VALUE)
    public @ResponseBody
    byte[] steg(@PathVariable String text, @RequestParam(value = "file", required = true) final MultipartFile file) throws IOException {

        userInputValidator.validate(file.getBytes(), text);
        return textStegService.steg(text, file.getBytes());
    }

Java 调试器不会在 Java 代码中停止,400 表示它没有到目前为止,请求中有问题,但我不确定是什么。

看起来你应该在构建 URL 参数时使用this.secretText而不是this.secretText.value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM