koa2使用koa-generator生成器创建的项目上传图片问题?

发布于 2022-09-11 23:21:44 字数 2207 浏览 18 评论 0

koa2使用koa-generator生成器创建的项目上传图片提示Cannot read property 'filename' of undefined,并且状态码提示500。

项目配置

{
  "name": "c",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "node bin/www",
    "dev": "./node_modules/.bin/nodemon bin/www",
    "prd": "pm2 start bin/www",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "debug": "^4.1.1",
    "koa": "^2.7.0",
    "koa-body": "^4.1.1",
    "koa-bodyparser": "^4.2.1",
    "koa-convert": "^1.2.0",
    "koa-json": "^2.0.2",
    "koa-logger": "^3.2.0",
    "koa-multer": "^1.0.2",
    "koa-onerror": "^4.1.0",
    "koa-router": "^7.4.0",
    "koa-static": "^5.0.0",
    "koa-views": "^6.2.0",
    "koa2-cors": "^2.0.6",
    "mysql": "^2.17.1",
    "pug": "^2.0.3"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
}

koa代码

const router = require("koa-router")();
const multer = require('koa-multer');
router.prefix("/upload");


//配置    
var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/images/')  //注意路径必须存在
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})

//加载配置
var upload = multer({ storage: storage })

router.post('/img', upload.single('face'), async (ctx, next) => {
    ctx.body = {
        filename: ctx.req.file.filename,//返回文件名
        body: ctx.req.body
    }
});

module.exports = router;

js代码

axios({
  method: "POST",
  baseURL: "upload/img",
  data: this.fileList[0].file,//这个是vant框架上传图片的
  headers: { "Content-Type": "application/x-www-form-urlencoded" }
})
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.log(error);
  });

this.fileList[0].file打印的内容

image

我是参考:https://www.itying.com/koa/article-index-id-103.html这个教程来弄的。

初次使用,还请大佬们见谅。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少女七分熟 2022-09-18 23:21:44

当前的情况下,看你的content-type是提交表单时候应该用的值,虽说图片也能用表单提交到后端,但看你的前后端代码,不是用的表单方式提交以及接收。

把content-type换成 multipart/form-data 试试?

const formData = new FormData()
formData.append('image', this.fileList[0].file, this.fileList[0].file.name)

之后,你把formData作为data传过去试一下。我也做过图片上传,恰好和你的实现逻辑差不多。我是这样做的

哽咽笑 2022-09-18 23:21:44

upload.single('face')注意这个

router.post('/img', upload.single('face'), async (ctx, next) => {
    ctx.body = {
        filename: ctx.req.file.filename,//返回文件名
        body: ctx.req.body
    }
})
      const formData = new FormData();
      formData.append(
        "image",
        this.fileList[0].file,
        this.fileList[0].file.name
      );

上面的【face】要与formData 的image要相同,不然还是报500并且提示Unexpected field

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文