0

console.log giving this but file is not uploading

{  
   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");
  });
});  
5
  • How much size of image you are trying to upload ? Commented Oct 31, 2017 at 5:27
  • 255kb ,,,,,,,,,, Commented Oct 31, 2017 at 5:31
  • Have you checked your file at ./public/uploads place with current working dir Commented Oct 31, 2017 at 5:32
  • you have mention your destination public/uploads in multer config Commented Oct 31, 2017 at 5:34
  • please check sample code gist.github.com/abachuk/fb66282ba623cb57948defe2209800a5 Commented Oct 31, 2017 at 5:35

2 Answers 2

2

only way to upload file via ajax is use FormData try this.

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))
  }

And action file

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)
    })
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you have not created proper destination to upload your image file at server side.

Please check your destination is exist /public/uploads in your server working dir.

Following links will help you on file upload functionality ,

  1. Uploading files with React.js and Node.js
  2. Sample Demo Code

Hopes this will help you !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.