- Newest
- Most votes
- Most comments
The main reason why file name could be undefined is because the action may be asynchronous, meaning at the time you perform the upload the react state doesn’t have the information.
Id suggest to try use a form onSubmit event and see if that helps.
Thanks for the reply I updated the code to use a Form's onSubmit but the filename is still "undefined" after the upload. Both versions of the code wait for the asynchronous operation. but I'm obviously missing something. Maybe I need to wait for a specific state ?
Here is the updated code with Form submit
import React from 'react';
import { uploadData } from 'aws-amplify/storage';
const StorageTest = () => {
const [file, setFile] = React.useState();
const handleChange = (event) => {
const selectedFile = event.target.files[0];
console.log('Selected file:', selectedFile);
setFile(selectedFile);
};
const handleSubmit = async (event) => {
event.preventDefault(); // Prevent the default form submission behavior
if (file) {
try {
console.log('File name:', file.name);
const result = await uploadData({
path: `public/docs/${file.name}`,
data: file,
});
console.log('File uploaded successfully', result);
} catch (error) {
console.error('Error uploading file', error);
}
} else {
console.error('No file selected for upload');
}
};
return (
<form onSubmit={handleSubmit}>
<input type="file" onChange={handleChange} />
<button type="submit">Upload</button>
</form>
);
};
export default StorageTest;
Ok I got it to work at last. I back tracked to the original code from the AWS Documentation Then replaced "path" with "key" in the uploadData function With this change the uploadData function works. The file is placed in a public\docs*.* folder, Here is the revised code.
import React from 'react';
import { uploadData } from 'aws-amplify/storage';
const StorageTest = () => {
const [file, setFile] = React.useState();
const handleChange = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = async () => {
if (file) {
try {
const filepath = `docs/${file.name}`;
const result = await uploadData({
//path: filepath,
key: filepath,
data: file
});
console.log('File uploaded successfully', result);
} catch (error) {
console.error('Error uploading file', error);
}
} else {
console.error('No file selected for upload');
}
};
return (
<div>
<input type="file" onChange={handleChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
}
export default StorageTest;
Relevant content
- asked 10 months ago
- asked a month ago
- asked 3 years ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 7 months ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 3 years ago