2017-02-14 131 views
1

我在后端使用feathers.js,在前端使用React,我需要实现一种上传图片的方式。我使用multer来处理上传(并且我尝试使用busboy),但我似乎无法获得上传的实际图片,或者至少可以在req.file上访问它。如何使用feathers.js和multer上传图片?

在客户端,我有:

<form method="post" enctype="multipart/form-data" action="/picture/upload"> 
    <input type="file" name="avatar" /> 
    <input type="submit" value="Submit" /> 
</form> 

/src/middleware/index.js我:

'use strict'; 

const uploadPicture = require('./uploadPicture'); 

const handler = require('feathers-errors/handler'); 
const notFound = require('./not-found-handler'); 
const logger = require('./logger'); 
var multer = require('multer'); 
const upload = multer({ dest: '../../client/img'}); 

module.exports = function() { 
    // Add your custom middleware here. Remember, that 
    // just like Express the order matters, so error 
    // handling middleware should go last. 

    const app = this; 

    app.post('/picture/upload', upload.single('avatar'), uploadPicture(app)); 
    app.use(notFound()); 
    app.use(logger(app)); 
    app.use(handler()); 
}; 

这是src/middleware/uploadPicture.js

'use strict'; 

module.exports = function(app) { 
    return function(req, res, next) { 
    console.log('req.file', req.file); 
    console.log('req.body', req.body); 

    }; 
}; 

req.file永远是不确定的,和req.body确实含有我上传的图像的名称。

我已经尝试在基本的Express项目上使用mutler和busboy进行测试,并且它完美地工作,所以这让我觉得它可能与中间件feathers.js使用并且可能会更改某些标头或东西,所以multer不能将文件追加到请求对象。

这是在中间件在src/app.js定义的顺序,这是服务器实例上运行:

app.use(compress()) 
    .options('*', cors()) 
    .use(cors()) 
    .use('/', serveStatic(app.get('client'))) 
    .use(bodyParser.json()) 
    .use(bodyParser.urlencoded({ extended: true })) 
    .configure(hooks()) 
    .configure(rest()) 
    .configure(services) 
    .configure(middleware); 

关于如何处理这种情况下的图片上传有什么想法?

+0

可能重复的[如何用feathersjs上传图片?](https://stackoverflow.com/questions/47174807/how-upload-image-with-feathersjs) –

+0

@BinUry不同的问题,这个问题已被回答,并且这个问题比较老。 –

回答

0

我正在使用反应,因此enctype不是supported HTML attribute。我应该在我的表格中使用encType。这解决了问题。