duanjigua5753 2019-04-12 01:02
浏览 101

文件上传,使用React JS和PHP服务器进行预览

I am trying to upload files in ReactJs . I need to implement a Little file Preview where a user can see the file he is about to upload Unfortunately, this preview is not working because I do not get the relative path of the file from the users computer from my file Array. Here is my Code for the file add function

onFilesAdded(files) {
    console.log(files);
    this.setState(prevState => ({
      files: prevState.files.concat(files)
    }));   
}

here is my render with my dropzone with the idea of attaching my files

   return (
        <Card className="space-above">
            <CardBody>
                <form name="form" onSubmit={this.handleSubmit}>
                   <div className="Upload">
                    <span className="Title">Change Profile Picture</span>
                    <div className="Content">
                      <div>
                        <Dropzone
                          onFilesAdded={this.onFilesAdded}

                        />
                      </div>
                      <div className="Files">
                             <Fragment>
                                {this.state.files.map(file => {
                                  return (
                                    <div key={file.name} className="Row">
                                        <img
                                            alt="Preview"
                                            key={file.name}
                                            src={file.name}
                                            style={previewStyle}
                                          />
                                          {console.log(file)}
                                        <span className="Filename">{file.name}</span>
                                        {this.renderProgress(file)}
                                    </div>
                                  );
                                })}
                            </Fragment>
                        </div>
                    </div>
                </div>

With the preview section.

Secondly, when I submit this files to my PHP Server, I am not able to receive the files. It returns no files found as the file value is an empty array.

Here is my code for the entire process. Any Help on this will be greatly appreciated or pointers.

import React, { Component,Fragment } from 'react';
import {Button, Card, CardBody} from 'mdbreact';
import request from 'superagent';
import Dropzone from "./dropzone/Dropzone";
import { Line } from 'rc-progress';
import Progress from "./progress/Progress";
import { Trans} from '@lingui/macro';
import { apiConstants } from '../_constants';
import { connect } from 'react-redux';

//this component is to upload a file into my server
class Muzikolupload extends Component {

     constructor(props) {
    super(props);
    this.state = {
      files: [],
      uploading: false,
      uploadProgress: {},
      successfullUploaded: false
    };

    this.onFilesAdded = this.onFilesAdded.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

    onFilesAdded(files) {
        console.log(files);
        this.setState(prevState => ({
          files: prevState.files.concat(files)
        }));   
    }

    //Handling Submision
    handleSubmit(event) {
        event.preventDefault();
        const {user} = this.props;
        let authKey = user.auth_key;
        const {files} = this.state;

        if (files.length>0) {
            this.setState({ submitted: true,nofile:false });
            //sent to my server now using
            let req = request.post(apiConstants.API_GENERAL_URL+'changepbackpic?access-token='+authKey);
            req.on('progress', event => {
                let percent = Math.floor(event.percent);
                if (percent >= 100) {
                    this.setState({ percent: 100 });
                } else {
                    this.setState({ percent: percent });
                }
            });
            const that = this;
            req.send(this.state);
            req.end((err, res) => {
                if(err){
                    console.log('error occured during file uploading', err);
                    this.setState({
                        completed:true,
                        message:'Field During Upload',
                        submitted:false,
                        files:[]
                    })
                }
                 if(res){
                     console.log('successfullUploaded', res);
                    this.setState({
                        completed:true,
                        message:'File succesfully uploaded',
                        submitted:false,
                        files:[]
                    })
                }
            });
        }
        else{
            this.setState({ nofile: true, submitted: false });
        }
    }

    renderProgress(file) {
        const uploadProgress = this.state.uploadProgress[file.name];
        if (this.state.uploading || this.state.successfullUploaded) {
          return (
            <div className="ProgressWrapper text-center">
              <Progress progress={uploadProgress ? uploadProgress.percentage : 0} />
              Drag and Drop or open to Change Picture

            </div>
          );
        }
  }

    render() {
        const previewStyle = {
          display: 'inline',
          width: 100,
          height: 100,
        };
        return (
            <Card className="space-above">
                <CardBody>
                    <form name="form" onSubmit={this.handleSubmit}>
                       <div className="Upload">
                        <span className="Title">Change Profile Picture</span>
                        <div className="Content">
                          <div>
                            <Dropzone
                              onFilesAdded={this.onFilesAdded}

                            />
                          </div>
                          <div className="Files">
                                 <Fragment>
                                    {this.state.files.map(file => {
                                      return (
                                        <div key={file.name} className="Row">
                                            <img
                                                alt="Preview"
                                                key={file.name}
                                                src={file.name}
                                                style={previewStyle}
                                              />
                                              {console.log(file)}
                                            <span className="Filename">{file.name}</span>
                                            {this.renderProgress(file)}
                                        </div>
                                      );
                                    })}
                                </Fragment>
                            </div>
                        </div>
                    </div>
                    {this.state.submitted &&
                        <Line percent={this.state.percent} strokeWidth='1' strokeColor='#2db7f5' strokeLinecap='square' />
                    }
                    {this.state.completed &&
                        <div className="help-block">
                            {this.state.message}
                        </div>
                    }
                    {this.state.nofile &&
                        <div className="help-block">
                           Please Attach a Picture
                        </div>
                    }
                    <div >
                        <Button type="submit" onClick={this.handleSubmit} className=" site-secondary-back btn-block"  ><Trans>Submit</Trans></Button>
                    </div>
                    </form>
                </CardBody>
            </Card>
        );
    }
}

function mapStateToProps(state) {
    const {user} = state.authentication;
    return {
        user,
    };
}

export default connect(
  mapStateToProps,
)(Muzikolupload)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog
    • ¥15 Excel发现不可读取的内容