【问题标题】:Meteor.js REST API POST image data using PostmanMeteor.js REST API 使用 Postman 发布图像数据
【发布时间】:2019-12-02 05:16:38
【问题描述】:

我正在为移动原生应用创建 API,需要创建一个 REST API 来上传用户个人资料图片。但是当我尝试在 POST 请求中上传图像时,它显示未定义。

这是我在 app/server/server.js 文件中的代码:

if(Meteor.isServer) {
   Router.route('/api/uploadpic/', { where: 'server' })
   .post(function () {

     let response;
     console.log(this.request.body.file);

     this.response.setHeader('Content-Type', 'application/json');
      this.response.end(JSON.stringify(response));

  });
}

花了很多时间后,我没有得到任何有用的东西。我需要为此使用任何软件包吗? 邮递员api请求http://prntscr.com/ojfcvj

【问题讨论】:

  • 没有人遇到过同样的问题

标签: api meteor iron-router


【解决方案1】:

1) 您必须创建一个 express 应用并与 Meteor WebApp 绑定
2)使用multer在nodejs和meteor上上传照片

import { WebApp } from 'meteor/webapp';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import path from 'path';
const multer = require('multer');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('*', cors());


// use multer({ dest: 'uploads/' }) if you have desire folder
// I used memory storage here
// 'avatar' is the post request field name for the file
const uploader = multer({ storage: multer.memoryStorage() }).single('avatar');
app.post('/uploads', uploader, Meteor.bindEnvironment(async(req, res, done) => {
   try {
        //you can get the file in req.file

        let fileName = req.file.originalname.replace(/\s/g, '_');
        let imageEncrypt = req.file.buffer.toString('base64');

        // Do whatever you want
   } catch (err) {
     res.status(404).end(err.message);
   }
}));

WebApp.connectHandlers.use(Meteor.bindEnvironment(app));

【讨论】:

  • 我已经尝试过了,但请告诉我你在哪里使用 app.post,因为它在流星 js 中不起作用
  • 你需要创建 express 应用并与 Meteor 绑定。请检查更新的答案
【解决方案2】:

不确定是否有帮助,但尝试将 Content Type 从 application/json 更改为 'multipart/form-data'

【讨论】:

    猜你喜欢
    • 2017-02-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多