文件没有上传反应js和nodejs使用multer

时间:2017-10-31 04:47:33

标签: node.js reactjs

console.log提供此文件但不上传文件

{  
   name:"sds",
   shop_name:"dfgdfg",
   address:"hfgdhf",
   phone:"dfgfgd",
   file:"C:\fakepath\favicon.png",
    …
}account_status:"pending"address:"hfgdhf"backup_database:""expiry:"2017-10-19"file:"C:\fakepath\favicon.png"name:"sds"phone:"dfgfgd"shop_name:"dfgdfg"__proto__:{  
   data:"File is uploaded",
   status:200,
   statusText:"OK",
   headers:{  
      …
   },
   config:{  
      …
   },
    …
}

component.js

 import { saveBasicUser, getOneBasicUser, uploadFile } from '../../actions/basicAction';

 class BasicUser extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: '', phone: '', account_status: '', address: '', shop_name: '', file: [], backup_database: '', expiry: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  //--------------------------------------------------------------------------
  handleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }
  //--------------------------------------------------------------------------
  handleSubmit(event) {
    event.preventDefault();
    var userId = this.props.params.id;
    var obj = {};
    obj["name"] = this.state.name
    obj["shop_name"] = this.state.shop_name
    obj["address"] = this.state.address
    obj["phone"] = this.state.phone
    obj["file"] = this.state.file
    obj["backup_database"] = this.state.backup_database
    obj["expiry"] = this.state.expiry
    obj["account_status"] = this.state.account_status
    console.log(obj)
    this.props.dispatch(saveBasicUser(obj))
  }


<form onSubmit={this.handleSubmit} encType="multipart/form-data">
              <div className="row">
                <div className="col-md-12">
                  <div className="form-group">
                    <label>
                      Name:
                   </label>
                    <input type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" />  .......................................
..........................................
                  </div>
                  <div className="form-group">
                    <label>File Upload</label>
                    <div className="form-group">
            <label>File Upload</label>
            <input type="file" className="form-control" name="file"value={this.state.file}b onChange={this.handleChange}  />

          </div>
                  </div>
                  <div className="btn-group" role="group">
                    <button type="submit" className="btn btn-success btn-lg">Submit</button>
                  </div>

action.js

export function saveBasicUser(obj) {
  console.log(obj)
  return (dispatch) => {

    return axios.post('/basic-user/saveUser', {
      headers: { 'content-type': 'multipart/form-data' },
      obj: obj
    }).then(function (res) {  
      browserHistory.push('/basic-dashboard');
      console.log(res)
    }).catch(function (err) {
      console.log(" err")
      console.log(err)
    })
  }
}

server.js

 var multer  = require('multer')

          var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './public/uploads')
},
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file')


app.post('/basic-user/saveUser',function(req,res){

  upload(req, res, function(err) {
      if(err) {
          return res.end("Error uploading file.");
      }
      res.end("File is uploaded");
  });
});  

2 个答案:

答案 0 :(得分:1)

通过ajax上传文件的唯一方法是使用FormData试试这个。

handleSubmit(event) {
    event.preventDefault();
    var userId = this.props.params.id;
    let formData = new FormData();
    formData.append('name', this.state.name);
    ...
    formData.append('file', this.state.file);
    ...

    this.props.dispatch(saveBasicUser(obj))
  }

和行动档案

export function saveBasicUser(obj) {
  return (dispatch) => {

    return axios.post('/basic-user/saveUser', obj).then(function (res) {  
      browserHistory.push('/basic-dashboard');
      console.log(res)
    }).catch(function (err) {
      console.log(" err")
      console.log(err)
    })
  }
}

答案 1 :(得分:0)

我认为您尚未创建正确的目标位置以在服务器端上传图像文件。

请检查服务器工作目录中的目的地是否存在If Not CopyRng Is Nothing Then Set CopyRng = Application.Union(CopyRng, .Rows(i)) Else Set CopyRng = .Rows(i) End If

以下链接将为您提供文件上传功能,

  1. Uploading files with React.js and Node.js
  2. Sample Demo Code
  3. 希望这会对你有帮助!