从客户端上传并发布文件(react js)到nodejs express server

时间:2018-04-02 13:01:29

标签: javascript node.js reactjs express file-upload

从我的客户端我有这个代码,在我创建的反应js componet中:

class PopinForm extends PureComponent {
  constructor() {
    super();
    this.state = {
      file : {},
      isError : {
        file : false,
      }
    };
  }


  //upload here
  _handleUploadFile = () => {
    uploadFile(this.state.file)
  };

  render() {
    <Root>
      <Input width="45%" type="file" onChange={ (e) => this.setState({file: e.target.files[0]}) } />
      <ButtonPopin width="20%" onClick={this._handleUploadFile}>
        Upload
      </ButtonPopin>
    </Root>
}
export default translate('translations')(PopinForm);

然后在我的导出模块中,这是函数uploadFile

export function uploadFile(file) {
  fetch(`${apiUrl}/upload`, {
    method: 'post',
    headers: headers,
    mode: 'cors',
    cache: 'default',
    resolveWithFullResponse: true,
    body: file,
  })
    .then(request => request.post())
    .catch((err) => {
      console.error(`>>>>>>> an internal error occurred: ${JSON.stringify(err, null, 3)}`)
    })
}

使用reactjs,我从输入类型文件中恢复文件数据。当我制作console.log(file)时,这是我的文件:

  

文件
  lastModified:1522422082000   lastModifiedDate:日期   2018-03-30T15:01:22.000Z
  名称:“test.xls”   大小:7105   键入:“application / vnd.openxmlformats-officedocument.spreadsheetml.sheet”   webkitRelativePath:“”

因此它与我从输入类型文件上传的正确文件匹配良好。

但是,在我的服务器端我使用multer,这是我用来恢复文件的方法,这里是index.js中的代码:

// instantiate multer storage to define the tmp folder path to store file
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'tmp/')
  },
  // register the file with his original name and extension
  filename: (req, file, cb) => {
    cb(null, file.originalname)
  },
})
// declare the upload method with storage path and filename registration
const upload = multer({storage: storage})

//  upload XLSX massive request import
app.post('/upload', upload.single('uploadRequests'), require(path.join(__dirname, 'some', 'path', 'to', 'uploadRequest.js')))

当我提交上传文件时,我有这样的错误: UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:12):TypeError:由于我提出的请求,无法读取未定义的属性'originalname'文件uploadRequests.js在这里:const fileName = req.file.originalname

这是uploadRequests.js的代码:

const uploadRequests = async (req, res) => {
  // get filename by req
  const fileName = req.file.originalname
  // instantiate excel class
  const workbook = new Excel.Workbook()

  workbook.xlsx.readFile(req.file.path)
    .then(async () => {
      // treatment on xlsx file test with postman exmaple and files, nothing went wrong here
      // fetch on database request and CRUD method to update or create data
      return res.json({message: 'massive import request success !', data: data})
    })
    .catch((err) => {
      throw new Error(`workbook readFile method return an ${err}`)
    })
}
module.exports = uploadRequests

我是nodejs的新手,我想知道如何在我的nodejs服务器上从客户端正确恢复文件。

0 个答案:

没有答案