2

i am trying very hard to upload file but no way i could find a clear solution . i have tried many ways but not working . Now the console shows me 200 and give me message that file is uploaded but file is not going in the folder . i ahve checked file size limit and folder is ok but dont know why its not working. could any help please.

///react component

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

 this.state = { file: []};

 handleChange(event) {

 this.setState({
 [event.target.name]: event.target.value, 
 file: 
 event.target.files}) 
 }

 handleSubmit(event) {
 event.preventDefault();
   var file = this.state.file

    let formData = new FormData();
    formData.append('file', file);

    // console.log(obj);
    console.log(formData);

    //  this.props.dispatch(saveBasicUser(obj ))
     this.props.dispatch(uploadFile(formData ))
  }


<form onSubmit={this.handleSubmit} encType="multipart/form-data">  
<input type="file" name = "file" onChange={this.handleChange} />
<button type="submit" className="btn btn-success btn-lg">Submit</button>

////////action part

 export function uploadFile(formData) {
  console.log(formData)
  return (dispatch) => {

    return axios.post('/upload_file', {
      headers: { 'content-type': 'multipart/form-data' },
      data: formData
    }).then(function (res) {  

      console.log(res)
    }).catch(function (err) {
      console.log(" err")
      console.log(err)
    })
  }
}

//////server part

var storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, './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('/upload_file', function(req, res){

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

  });

1 Answer 1

1

I have found the solution at last.

react JS

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getOneBasicUser ,uploadFile} from '../../actions/basicAction';
//--------------------------------------------------------------------------
class Upload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };


        this.handleChange = this.handleChange.bind(this);
        this.handleFile = this.handleFile.bind(this);
      }
      //--------------------------------------------------------------------
      //--------------------------------------------------------------------------
      handleChange(event) {
        this.setState({
          [event.target.name]: event.target.value
        });
      }
      //--------------------------------------------------------------------------
      handleFile(e) {

            e.preventDefault();

            var id = this.props.params.id;

            console.log(id);

            var formData = new FormData($('form')[0]);

            var isFileExist = !!$('input[type=file]')[0].files[0];



            if (isFileExist) {

                $.ajax({

                    url:  '/upload_file/'+ id,

                    type: 'POST',

                    data: formData,

                    xhr: function () {

                        var xhr = new window.XMLHttpRequest();

                        xhr.upload.addEventListener("progress", function (e) {

                            if (e.lengthComputable) {

                                $('progress').attr({value: e.loaded, max: e.total});

                                $('#status').empty().text(parseInt((e.loaded / e.total * 100)) + '%');

                            }

                        }, false);

                        return xhr;

                    }.bind(this),

                    success: function (data) {

                        this.setState({

                            data: data

                        });

                        $('#status').empty().text('File Uploaded!');

                    }.bind(this),

                    error: function (xhr, status, err) {

                        console.log( err);

                    }.bind(this),

                    cache: false,

                    contentType: false,

                    processData: false

                });

            } else {

                $('#status').empty().text('Please choose the file.');

            }

            }
      //--------------------------------------------------------------------------
      render() {




        return (
          <div className="container ca-container">
            <div className="row">
              <div className="col-md-12">
                <h2> Upload File </h2>
                <hr />
              </div>
            </div>
               <form onSubmit={this.handleFile} encType="multipart/form-data">
              <div className="row">
                <div className="col-md-12">
                <div className="col-md-6">
                <h3 id="status" className ="label label-success"></h3>
                <div className="form-group">
                      <label>
                        Name:
                   </label>
                      <input  type="file" className="form-control" name="BasicUserFile"  onChange={this.handleChange} placeholder="file" />
                    </div>
                  <div className="btn-group" role="group">
                  <button type="submit" value="Upload File" className="btn btn-success btn-lg">Upload</button>
                  </div>
                  </div>

                </div>
              </div>
            </form>
          </div>
        );
      }



}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
  return {
    //basicUser: state.basicUser.basicUser

  };
};

export default connect(mapStateToProps)(Upload);

////server.js

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


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


app.post('/upload_file/:id', function(req, res){

  console.log("000000000000000000000000000000000000000000000000")

  console.log(req.params)

  console.log("000000000000000000000000000000000000000000000000")




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

  });
Sign up to request clarification or add additional context in comments.

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.