ReactJS file upload - reactjs

I am trying to upload a file using reactjs. I am not getting the right log. Before uploading, I wanted to see the output. But not getting the result.
Here what I have tried
state = {
selectedFile: null
}
fileChangedHandler = event => {
this.setState({
selectedFile: event.target.files[0]
})
console.log(this.state.selectedFile)
}
uploadHandler = () => {
const formData = new FormData()
var fd = formData.append("data", this.state.selectedFile, this.state.selectedFile.name)
console.log(fd)
}
render() {
return (
<div>
<input type="file" onChange={this.fileChangedHandler} />
<button onClick={this.uploadHandler}>Upload!</button>
</div>
);
}

Try this
// Create your FormData object
var formData = new FormData();
formData.append('key1', 'value1'); // Test data
formData.append('key2', 'value2'); // Test data
// Display the key/value pairs array
for (var pair of formData.entries()) {
console.log(pair);
}

Related

input type file doesn't act independently for different children in a map in react js

I am iterating a list of file inputs in react through a map function
render() {
const {
form,
loading,
filledIndex,
} = this.state;
return (
map function
{form.a &&
form.a.map((prop, index) => (
upload component
<label
htmlFor="proofDocUrl"
className="save-form-btn-personal"
>
Upload
</label>
<input
type="file"
accept=".png,.jpg"
id="proofDocUrl"
name="proofDocUrl"
onChange={(e) => this.handleChangeUpload(e, index)}
onClick={(event) => {
event.target.value = null;
}}
/>
handleChangeUpload function. send file to server and fetch url
handleChangeUpload = async (e, index) => {
if (e.target.files) {
let formData = new FormData();
formData.append("b", e.target.files[0]);
this.setState({ loading: true });
const form = { ...this.state.form };
let documentUpload =
await A_service.A_api(formData);
if (documentUpload) {
if (documentUpload.data && documentUpload.data.data) {
documentUpload = documentUpload.data.data;
}
form.x[index][e.target.name] =
documentUpload.parameter;
}
this.setState({ loading: false, form });
}
};
states that are used. form state has x component which is iterated through a map.
proofDocUrl stores image url
form: {
x: [],
},
formLocal: {
proofDocUrl: "",
},
when a new object is added to form.x state and when it creates a new child in render the file input acts as if its the same for all childeren.
when a image is uploaded in one file component in one child, same will be uploaded for all childern.
How to make each file component in each child acts independently.

Upload image file to AWS S3 React JS

Currently I have code working where it will upload multiple files to s3.
My problem is, the image files are corrupted and will not open.
I want to upload them as images, or Form data, not encoded in base64 format.
How would I go about solving this?
I apologize for the sloppy code.
My Code
import { API, Storage } from "aws-amplify";
import { S3Album } from 'aws-amplify-react';
function Upload(props) {
async function readContent(fileToUpload) {
return new Promise((accept, reject) => {
const reader = new FileReader();
reader.readAsDataURL(fileToUpload);
reader.onload = () => accept({
name: fileToUpload.name,
type: fileToUpload.type,
content: reader.result
});
reader.onerror = () => reject();
});
}
async function handleSubmit(event) {
event.preventDefault();
const filesAsArray = [...fileToUpload.current.files];
const fileInfo = Promise.all(filesAsArray.map(readContent))
.then(files => Promise.all(files.map(uploadFile)))
.then(console.log);
return false;
}
async function uploadFile(fileToUpload) {
setShowLoading(true);
const filename = `${job.jobId}/${fileToUpload.name}`;
const stored = await Storage.put(filename, fileToUpload.content, {
contentType: fileToUpload.type
});
return new Promise(accept => {
setTimeout(() => accept(fileToUpload), 1000);
});
setShowLoading(false);
}
return(
<h4 style={centerText}> Please upload all images for {(job.streetAddress)} </h4>
<br></br>
<br></br>
<S3Album path={job.jobId}/>
<form onSubmit={handleSubmit}>
<input multiple type="file" ref={fileToUpload}></input>
<Button expand="block" color="primary" strong="true" size="default" type="submit"> Upload </Button>
</form>
);
}
export default withRouter(Upload);
const stored = await Storage.put(filename, fileToUpload, {contentType:fileToUpload.type});
Storage.put() can take in a file object directly, so no need for FileReader().
See image example: https://aws-amplify.github.io/docs/js/storage

Removing FilePond file after upload React

Ok I am at my wits end here. I am using FilePond with React in a functional component using Hooks. I am not using FilePond to handle the actual upload, just setting the state with the files, my simplified version is this:
The Filepond:
<FilePond
onupdatefiles={fileItems => handleFilepondUpdate(fileItems)}
/>
</Form.Field>
The handle update:
const handleFilepondUpdate = fileItems => {
if (fileItems.length === 0) {
addAttachment({
...picture,
bugAttachment: null
});
} else {
addAttachment({
...picture,
bugAttachment: fileItems[0].file
});
}
};
The state:
const [picture, addAttachment] = useState({
bugAttachment: ""
});
const { bugAttachment } = picture;
And finally my upload and clear the input state:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("email", props.user[0].email);
fd.append("bugDescription", bugDescription);
fd.append("bugAttachment", bugAttachment);
addBug(fd).then(() => {
setBug({
bugDescription: ""
});
});
};
So how would I go about removing the FilePond file after the form is sent through?
Try clearing the bugAttachment property inside onSubmit using addAttachment hook
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("email", props.user[0].email);
fd.append("bugDescription", bugDescription);
fd.append("bugAttachment", bugAttachment);
addBug(fd).then(() => {
setBug({
bugDescription: ""
});
addAttachment({
...picture,
bugAttachment:""
});
});
};
Update:
It seems like that you have not used the files prop with your picture state,Try something like this.
<FilePond
files={bugAttachment}
onupdatefiles={fileItems => handleFilepondUpdate(fileItems)}
/>

Input file(jpg/png) uploading and showing are not working in Reactjs?

File Button is not showing the jpeg image after uploading in locally
Below is the code i have written in react js...
categoryImageArray = [];
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
categoryImageArray.push(e.target.result);
}
}
and below is the JSX code
**IMG SRC**
<div>
<img src = { "'" + categoryImageArray[0] + "'" } />
</div>
Input File
<input type="file" onChange = { this.getCategoryImageLink } />
You have to use state for this,set the value of categoryImageArray in state and change it's value in getCategoryImageLink function
Try this.
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
this.setState({categoryImageArray: ...this.state.categoryImageArray,e.target.result});
}
}

Upload and send data with axios in reactjs

How can i get data from input with type file and send it with axios in reactjs?
I found something about formData but i didn't find anything about get data from input and send it with axios.
thanks.
Lets assume that you have all the input data along with the file in your state like
constructor(props) {
super(props);
this.state = {
file : someName.txt, // file input
stateName : 'MP' // Text Input
date : 07/08/2018 // Date input
}
}
Now, in you handelSubmit method construct a JSON Object
handelSubmit = () => {
const { file, stateName, date } = this.state;
let data = [];
data['file'] = file;
data['stateName'] = stateName;
data['date'] = date;
// a function which makes a axios call to API.
uploadFile(data, (response) => {
// your code after API response
});
}
Here is a function to make a API call by axios
uploadFile(data, callback) {
const url = ''; // url to make a request
const request = axios.post(url, data);
request.then((response) => callback(response));
request.catch((err) => callback(err.response));
}
UPDATED :
Text On Change method to set state
handelOnChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
Method on upload of file to set into state
handelOnUploadFile = (event) => {
this.setState({
file : event.target.files
})
}
Here is a JSX code.
render() {
return(
<div>
<input type="file" onChange={this.handelOnUploadFile} /> {/* input tag which to upload file */}
<input type="text" name="stateName" onChange={this.handelOnChange} /> {/* text input tag */}
<button type="submit" onClick={this.handelSubmit}> UPLOAD </button>
</div>
)
}
Hope it helps you.

Resources