2017-08-26 100 views
2

無論我如何實現文件上傳,當檢查Express中請求的req.file屬性時,我會得到undefinedMulter通過ReactJS返回`undefined`用於文件上傳

..

陣營代碼

組件:

import Files from 'react-files'; 

<form encType="multipart/formdata"> 
    <Files 
     ref='files' 
     onChange={this.onFileUpload}> 
    </Files> 
</form> 

方法:

onFileUpload (files) { 

    let reader = new FileReader(); 

    reader.onload = upload => { 
     this.setState({ 
      dataURI: upload.target.result 
     },() => { 

      if (typeof appState.balance == 'number' && appState.balance > 0) { 
       appState.onFileAdd(files, this.state.dataURI); 

      } else { 
       this.setState({ modal: true }); 
      } 

     }); 
    } 

    reader.readAsDataURL(files[files.length - 1]); 
} 

這正常工作;該狀態中的dataURI值是合法的並且設置正確。

..

API調用代碼

export async function funFile(name, dataURI) { 
    let data = new FormData(); 

    data.append('file', dataURI); 
    data.append('name', name); 

    return await fetch('http://localhost:1185/fun', 
    { method: 'POST', data }).then(res => { 
     if (res.ok && res.status == 200) { 
      return res.json(); 
     } else { 
      return null; 
     } 
    }); 
} 

檢查data這裏返回預期FormData對象,雖然沒有看到指定的namefile屬性(這是否是因爲他們的能力沒有正確分配,或者這是預期行爲,我不確定)。

..

快速代碼不管什麼,我在這一點上做的

var multer = require('multer'); 
var upload = multer({ destination: 'uploads/' }); 

app.post('/fun', upload.single('file'), (req, res) => { 

    console.log('file', req.file); 
    console.log('files', req.files); 

    // both of these return undefined 
}); 

,請求返回沒有文件數據。 req.body屬性也是空的。

我不確定事情在這裏出了什麼問題,並且從這個實現的所有可能的教程和演練中我已經嘗試了所有可能的語法變體,我可以想到,所以任何幫助都會被讚賞!

+0

那麼你的'upload.single( '文件')'呢? – Panther

回答

0

我相信問題是讀取文件作爲數據url。忘記FileReader。您不需要閱讀任何內容,只需將文件對象傳遞給您的FormData即可完成設置。

的onChange

onFileUpload (files) { 

    this.setState({ 
    file: files[files.length-1] 
    },() => { 

    if (typeof appState.balance == 'number' && appState.balance > 0) { 
     appState.onFileAdd(files, this.state.file); 
    } else { 
     this.setState({ modal: true }); 
    } 

    }); 
} 

API調用

export async function funFile(name, file) { 
    let data = new FormData(); 

    data.append(name, file); // name here should be avatar 

    return await fetch('http://localhost:1185/fun', 
    { method: 'POST', data }).then(res => { 
     if (res.ok && res.status == 200) { 
      return res.json(); 
     } else { 
      return null; 
     } 
    }); 
}