Skip to content

Amplify Storage S3 uploadData function filename issue

0

I added storage to my Amplify React App. Read the AWS Documentation https://docs.amplify.aws/react/build-a-backend/storage/upload-files/ The uploadData function does upload the file for me but the filename is reported in the AWS S3 Console as "undefined". I can tell its the right file based on file size, ie if I upload a different file the filesize updates to match, however again the file is called "undefined"

Here is the 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 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 (
		<div>
		  <input type="file" onChange={handleChange} />
		  <button onClick={handleUpload}>Upload</button>
		</div>
	  );
	}

	export default StorageTest;
3개 답변
0

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.

전문가
답변함 일 년 전
전문가
검토됨 일 년 전
0

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;
답변함 일 년 전
0

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;
답변함 일 년 전
전문가
검토됨 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.