首页 > 解决方案 > VueJS-Axios:将图像文件上传到 localhost 会出现错误:POST 404(未找到)。为什么?

问题描述

我有一个非常简单的 VueJS Axios 应用程序来理解通过 Axios 上传文件,但是文件没有保存到http://localhost/upload目录中。

我收到 2 个错误:

POST http://localhost:8080/upload 404 (Not Found)

createError.js?f777:16 Uncaught (in promise) Error: Request failed with status code 404
    at createError (eval at <anonymous> (build.js:1359), <anonymous>:16:15)
    at settle (eval at <anonymous> (build.js:1442), <anonymous>:17:12)
    at XMLHttpRequest.handleLoad (eval at <anonymous> (build.js:1338), <anonymous>:59:7)

这是完成的代码:

<template>
  <div id="app">
    <input type="file" @change="getFile">
    <button @click="uploadFile">Upload file</button>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: "App",

  data() {
    return {
      selectedFile: null
    }
  },

  methods: {
    getFile() {
      let file = event.target.files[0]
      this.selectedFile = file
    },
    uploadFile() {
        let fd = new FormData()
        fd.append('image', this.selectedFile, this.selectedFile.name)
        axios.post('/upload', fd)
          .then(res => {
              console.log(res);
          })
    }
  }
}
</script>

更新

服务器端代码 (formidable.js)

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*")
  res.setHeader("Content-Type", 'text/html');
  console.log("TRIGGERED");
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Admin/Desktop/uploadTest/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(9090);

更新客户端:

<template>
  <div id="app">
    <input type="file" @change="getFile">
    <button @click="uploadFile">Upload file</button>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: "App",

  data() {
    return {
      selectedFile: null
    }
  },

  methods: {
    getFile() {

      let file = event.target.files[0]
      this.selectedFile = file
    },
    uploadFile() {
        let fd = new FormData()
        fd.append('myImg', this.selectedFile, this.selectedFile.name)
        axios.post('http://localhost:9090/formidable', fd)
          .then(res => {
              console.log(res);
          })
    }
  }
}
</script>

服务器端代码的问题是我不知道如何检索发送到服务器的文件数据。这个 console.log("TRIGGERED") 被解雇但无法超越。

谢谢

标签: node.jsvue.jsaxios

解决方案


推荐阅读