Reputation: 12463
I have API
which receives POST file upload
like this
curl -X POST -F upfile=@_mat/test.wav http://localhost:8008/upload/
The file is send as upfile
my source code is like this below where can I set upfile
??
import React,{Component} from 'react';
import axios from 'axios';
const g_port = 8008;
const g_api = `http://localhost:${g_port}`;
class SpPage extends Component {
state = {
selectedFile: null
};
onFileChange = event => {
// Update the state
this.setState({ selectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.selectedFile,
this.state.selectedFile.name
);
console.log(this.state.selectedFile);
// Request made to the backend api
// Send formData object
axios.post(`${g_api}/upload/`, formData)
.then(res =>{
console.log(res);
})
.catch(err=>{
console.log(err);
});
};
// File content to be displayed after
// file upload is complete
fileData = () => {
if (this.state.selectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>File Name: {this.state.selectedFile.name}</p>
<p>File Type: {this.state.selectedFile.type}</p>
<p>
Last Modified:{" "}
{this.state.selectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose before Pressing the Upload button</h4>
</div>
);
}
};
render() {
return (
<div>
<h1>
GeeksforGeeks
</h1>
<h3>
File Upload using React!
</h3>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>
Upload!
</button>
</div>
{this.fileData()}
</div>
);
}
}
export default SpPage;
Upvotes: 1
Views: 431
Reputation: 8925
You already have a formData
and send it to the /upload
endpoint in the body of the request. so you can append your upfile
in the current formData
:
// rest of the codes ...
formData.append(
"myFile",
this.state.selectedFile,
this.state.selectedFile.name
);
formData.append(
"upfile",
myWaveFile
)
Upvotes: 2