How to Get Name of File From Upload Button Material Ui

In many existent world scenarios we require various types of files to be uploaded from user. In today'south tutorial we are going to embrace bones file upload using reactjs.

Then allow's get started:

We are going to make changes in the uploadScreen component that we created in the login tutorial here.We are going to need react-dropzone and fabric-ui npm modules for handling file upload and designing app ui.Install them past running the following command in your project:

          npm install --relieve react-dropzone material-ui        

Now permit'south get back to editing uploadScreen.js:

          import Dropzone from 'react-dropzone';
....
class UploadScreen extends Component {
render() {
render (
<div className="App">
<Dropzone onDrop={(files) => this.onDrop(files)}>
<div>Try dropping some files here, or click to select files to upload.</div>
</Dropzone>
</div>
)
}
}

This volition create basic dropzone for selecting files from directories.Side by side we create onDrop handler to temporarily save selected files:

          class UploadScreen extends Component {
constructor(props){
super(props);
this.state={
filesToBeSent:[],
}
}
onDrop(acceptedFiles, rejectedFiles) {
// panel.log('Accepted files: ', acceptedFiles[0].name);
var filesToBeSent=this.state.filesToBeSent;
filesToBeSent.push button(acceptedFiles);
this.setState({filesToBeSent});
}
...
}

This will allow users to select multiple files before uploading them. Next we will create a filesPreview div where all of user selected files will be displayed until the user is fix to upload files:

          import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Dropzone from 'react-dropzone';
import FontIcon from 'material-ui/FontIcon';
import {blue500, red500, greenA200} from 'material-ui/styles/colors';
class UploadScreen extends Component {
constructor(props){
super(props);
this.state={
filesPreview:[],
filesToBeSent:[],
printcount:10,
}
}
onDrop(acceptedFiles, rejectedFiles) {
// console.log('Accepted files: ', acceptedFiles[0].proper name);
var filesToBeSent=this.state.filesToBeSent;
if(filesToBeSent.length < this.state.printcount){
filesToBeSent.push(acceptedFiles);
var filesPreview=[];
for(var i in filesToBeSent){
filesPreview.button(<div>
{filesToBeSent[i][0].name}
<MuiThemeProvider>
<a href="#"><FontIcon
className="material-icons customstyle"
color={blue500}
styles={{ top:10,}}
>articulate</FontIcon></a>
</MuiThemeProvider>
</div>
)
}
this.setState({filesToBeSent,filesPreview});
}
else{
alert("You accept reached the limit of printing files at a time")
}
}
render() {
return (
<div className="App">
<Dropzone onDrop={(files) => this.onDrop(files)}>
<div>Effort dropping some files here, or click to select files to upload.</div>
</Dropzone>
<div>
Files to exist printed are:
{this.state.filesPreview}
</div>
</div>
)
}
}

Here we take set max file choice count to x which can exist adjusted based on your needs.On every file selection onDrop function takes previously selected files as input,appends newly selected file and updates filePreview div to display files.

Next we are going to brand UI a little better and add an upload button to send files to server one time user has selected all the files:

          class UploadScreen extends Component {
...
return() {
return (
<div className="App">
<MuiThemeProvider>
<div>
<AppBar
championship="Print Files"
/>
</div>
</MuiThemeProvider>
<centre>
<div>
You can upload upto {this.state.printcount} files at a fourth dimension.
</div>
<Dropzone onDrop={(files) => this.onDrop(files)}>
<div>Endeavour dropping some files hither, or click to select files to upload.</div>
</Dropzone>
<div>
Files to be printed are:
{this.state.filesPreview}
</div>
</heart>
<div>
{this.state.printingmessage}
</div>
<MuiThemeProvider>
<RaisedButton label="Print Files" principal={true} mode={way} onClick={(event) => this.handleClick(event)}/>
</MuiThemeProvider>
</div>
</div>
);
}
}
const manner = {
margin: 15,
};
export default UploadScreen;

Every bit you tin can see nosotros need to implement handleClick in the onClick handler in which we volition upload files to server.We are going to use superagent module to upload files to server which can be installed past running the following control:

          npm install --relieve superagent        

The handleClick office is implemented as follows:

          /*
Module:superagent
superagent is used to handle post/go requests to server
*/
var request = crave('superagent');
var apiBaseUrl = "http://localhost:4000/api/";
class UploadScreen extends Component {
....
handleClick(event){
// console.log("handleClick",result);
var self = this;
if(this.country.filesToBeSent.length>0){
var filesArray = this.state.filesToBeSent;
var req = request.post(apiBaseUrl+'fileupload');
for(var i in filesArray){
// panel.log("files",filesArray[i][0]);
req.attach(filesArray[i][0].name,filesArray[i][0])
}
req.end(part(err,res){
if(err){
console.log("error ocurred");
}
console.log("res",res);
alert("File printing completed")
});
}
else{
alert("Please upload some files first");
}
}
...
}

In the handleClick function nosotros first check if user has selected any files,then nosotros shop fileToBeSent in a local variable fileArray and attach each file with name to req variable responsible for sending request to backend. I have created backend apis in nodejs which I will exist covering in next tutorial.For now just presume that there is a fileupload route running on port 4000 on localhost which will take files from frontend in a post request.

Here is a screenshot of the final app screen:

fileuploadscreenshot

The user is greeted with alarm that file take finished uploading once nosotros receive a response from backend apis. That finishes off our today'south tutorial. Check out some bonus tips and you can see the complete code at end of bonus tips.

Bonus Tips:

1)We can proceed the submit button disabled when user clicks it until nosotros finish file uploading to server in order to prevent multiple upload requests to server.Yous can also add loading spinner or uploading message until uploading is finished.

2)Material UI supports in app drawer which can be modified further to add more features like upload history and user management.

There are many additions that can be done to the lawmaking which I take covered in the bonus tips sections and covered some of them in complete code uploaded on github gist here.

In case yous demand to develop backend apis in nodejs for handling filee upload in the backend and so you can find the tutorial here.

Connect Deeper:

Follow our facebook page to become notified about side by side tutorial in the series in which I volition cover retrieving files uploaded in the past past the user here: Technoetics or simply follow our publication on medium.

numbersrowend.blogspot.com

Source: https://medium.com/technoetics/handling-file-upload-in-reactjs-b9b95068f6b

0 Response to "How to Get Name of File From Upload Button Material Ui"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel