2017-02-14 132 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。這解決了問題。